/// <summary>
        /// Выращивание регионов по заданному признаку
        /// </summary>
        /// <param name="image">Серое изображение</param>
        public void FindComponents(GreyImage image)
        {
            try
            {

                if (image == null)
                    throw new ArgumentNullException("Null image in FindComponents");

                this.Regions.Clear();
                this.RegionsEquivalents.Clear();

                DeleteTrashLines(image);

                if (this.Feature == UnifyingFeature.StrokeWidth)
                {
                    if (this.ConnectivityType == Interface.ConnectivityType.FourConnectedRegion)
                        FirstPassStrokeWidth4Connectivity(image);
                    else
                        FirstPassStrokeWidth8Connectivity(image);
                }
                SecondPass(image);
                DefineRegions(image);
                CountRegionsParameters();
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public GreyImage ToGreyImage(Bitmap bitmap)
        {
            try
            {
                if (bitmap == null)
                    throw new ArgumentNullException("Null bitmap in ToGreyImage");

                int width = bitmap.Width;
                int height = bitmap.Height;
                GreyImage greyImage = new GreyImage(width, height);
                for (int i = 0; i < height; i++)
                    for (int j = 0; j < width; j++)
                    {
                        Color color = bitmap.GetPixel(j, i);
                        if (color.R != color.G || color.R != color.B || color.G != color.B)
                            throw new ArgumentException("Bitmap must be greyscale in ToGreyImage");
                        greyImage.Pixels[i, j].Color.Data = color.R;
                    }
                return greyImage;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Вычисление градиента изображения
        /// </summary>
        /// <param name="image">Изображение</param>
        private void CountGradient(GreyImage image)
        {
            try
            {
                GreyImage copyImage = (GreyImage)image.Copy();

                int imageHeight = image.Height - 1;
                int imageWidth = image.Width - 1;

                for (int i = 0; i < imageHeight; i++)
                    for (int j = 0; j < imageWidth; j++)
                    {
                        int gradientX = Math.Abs(copyImage.Pixels[i, j].Color.Data - copyImage.Pixels[i + 1, j].Color.Data);
                        int gradientY = Math.Abs(copyImage.Pixels[i, j].Color.Data - copyImage.Pixels[i, j + 1].Color.Data);

                        int gradient = gradientX + gradientY;
                        if (gradient > ColorBase.MAX_COLOR_VALUE)
                            gradient = ColorBase.MAX_COLOR_VALUE;
                        image.Pixels[i, j].Color.Data = (byte) gradient;
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Определяет границы серого изображения (многопоточная)
        /// </summary>
        /// <param name="image">Серое изображение</param>
        /// <param name="threadsNumber">Число потоков</param>
        public GreyImage Detect(GreyImage image, int threadsNumber)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Detect");
                if (threadsNumber <= 0)
                    throw new ArgumentException("Error threadsNumber in Detect");

                GreyImage smoothedImage = this.SmoothingFilter.Apply(image, threadsNumber);
                _greySmoothedImage = (GreyImage)smoothedImage.Copy();
                smoothedImage = this.EdgeDetectionFilter.Apply(smoothedImage, threadsNumber);
                SetGradientDirection(smoothedImage);
                NonMaximaSuppression(smoothedImage);
                DoubleTresholding(smoothedImage);
                EdgeTrackingByHysteresis(smoothedImage);
                SetEdgesColor(smoothedImage);

                return smoothedImage;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Бинаризация методом Ниблака
        /// </summary>
        /// <param name="image"></param>
        public void Binarize(GreyImage image)
        {
            try
            {
                int windowSize = this.WindowSize;
                int lowIndex = windowSize / 2;
                int highIndexI = image.Height - lowIndex;
                int highIndexJ = image.Width - lowIndex;

                GreyImage copyImage = (GreyImage)image.Copy();

                for (int i = lowIndex; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        double matExp = CountMatExp(copyImage, i, j);
                        double sigma = CountSigma(copyImage, i, j, matExp);

                        int treshold = (int) (matExp + this.K * sigma);
                        if (image.Pixels[i, j].Color.Data < treshold)
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                        else
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Вычисляет порог бинаризации для изображения
        /// </summary>
        /// <param name="image">Изображение</param>
        /// <returns></returns>
        public int Countreshold(GreyImage image)
        {
            try
            {
                int imageHeight = image.Height;
                int imageWidth = image.Width;

                byte minColor = 0;
                byte maxColor = 0;

                GetMinMaxColorValues(image, ref minColor, ref maxColor);
                int[] histogram = CreateHistogram(image, minColor, maxColor - minColor + 1);

                int P = 0, iP = 0;
                CountMatExp(histogram, ref P, ref iP);

                this.Treshold = GetTreshold(histogram, P, iP) + minColor;

                return this.Treshold;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Example #7
0
        /// <summary>
        /// Применение морфологической операции расширения к контурному изображению
        /// </summary>
        /// <param name="image"></param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");

                GreyImage copyImage = (GreyImage)image.Copy();

                int filterSize = this.Size;
                int lowIndex = filterSize / 2;
                int highIndexI = image.Height;
                int highIndexJ = image.Width - lowIndex;
                for (int i = 0; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        if (copyImage.Pixels[i, j].Color.Data == ColorBase.MIN_COLOR_VALUE)
                        {
                           //ool borderPixelFound = false;
                            for (int k = 0; k < filterSize; k++)
                                image.Pixels[i, k + j - lowIndex].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                                // (copyImage.Pixels[i, k + j - lowIndex].Color.Data == ColorBase.MIN_COLOR_VALUE)
                                  //borderPixelFound = true;
                          //  if (borderPixelFound)
                            //    image.Pixels[i, j].Color.Data = (byte) ColorBase.MIN_COLOR_VALUE;
                        }
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Example #8
0
        public static void Recognize()
        {
            int n_images = Workspace.Images.Length;
            int i_image = n_images - 1;
            //i_image = 0;
            i_image = 2;
            string fileName = Workspace.Images[i_image];

            string imageFile = Path.Combine(Workspace.InputFolder, fileName);

            string language = "eng";
            int oem = (int)eOcrEngineMode.OEM_DEFAULT;

            string name = Path.GetFileNameWithoutExtension(imageFile);
            {
                using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
                {
                    using (GreyImage greyImage = GreyImage.FromImage(bmp))
                    {

                        ImageThresholder thresholder = new AdaptiveThresholder();
                        using (BinaryImage binImage = thresholder.Threshold(greyImage))
                        {
                            DateTime started = DateTime.Now;
                            DateTime ended = DateTime.Now;

                            Rectangle[] rois = new Rectangle[] { 
                                Rectangle.FromLTRB(807, 43, 1351, 613),
                                Rectangle.FromLTRB(4, 604, binImage.Width - 15, binImage.Height-35)
                            };

                            int nROIs = rois.Length;

                            string[] texts = new string[nROIs];
#if PARALLEL
                            Parallel.For(0, nROIs, delegate(int iROI) 
#else
                            using (TesseractProcessor processor = new TesseractProcessor())
                            for (int iROI = 0; iROI < nROIs; iROI++)
#endif
                            {
#if PARALLEL
                                using (TesseractProcessor processor = new TesseractProcessor())
#endif
                                {
                                    Rectangle roi = rois[iROI];
                                    {                                    
                                        //oem = (int)eOcrEngineMode.OEM_TESSERACT_CUBE_COMBINED;
                                        processor.Init(Workspace.TessdataFolder, language, oem);
                                        processor.UseROI = true;
                                        processor.ROI = roi;
                                        unsafe
                                        {                                            
                                            texts[iROI] = processor.RecognizeBinaryImage(
                                               binImage.BinaryData, binImage.Width, binImage.Height);
                                        }
                                    }
                                }
                            }
 public SWTFilter(GreyImage gaussSmoothedImage)
 {
     if (gaussSmoothedImage == null)
         throw new ArgumentNullException("Null gaussSmoothedImage in ctor");
     this._gaussSmoothedImage = gaussSmoothedImage;
     this._rayMaxIntensityDirection = new List<Ray>();
     this._rayMinIntensityDirection = new List<Ray>();
 }
 public MatrixFilterData(GreyImage image, int startI, int endI, int startJ, int endJ)
 {
     this.GreyImage = image;
     this.StartIndexI = startI;
     this.EndIndexI = endI;
     this.StartIndexJ = startJ;
     this.EndIndexJ = endJ;
     this.RGBImage = null;
 }
        public void TestSobelFilter3()
        {
            //arrange
            EdgeDetectionFilter sobel = new SobelFilter();
            GreyImage image = new GreyImage(2, 3);

            //act
            sobel.Apply(image);
        }
Example #12
0
    static oTesseractRequest __ocrExecute2(oTesseractRequest req, Bitmap bitmap)
    {
        using (TesseractProcessor processor = new TesseractProcessor())
        {
            processor.InitForAnalysePage();
            using (GreyImage greyImage = GreyImage.FromImage(bitmap))
            {
                //greyImage.Save(ImageFormat.Bmp, outFile2);

                ImageThresholder thresholder = new AdaptiveThresholder();
                using (BinaryImage binImage = thresholder.Threshold(greyImage))
                {
                    DocumentLayout doc = null;
                    switch (req.command)
                    {
                    case TESSERACT_COMMAND.GET_TEXT:
                        //string s = tes.GetText().Trim();
                        //req.output_text = s;
                        //req.output_count = s.Length;
                        req.ok = 1;
                        break;

                    default:
                        unsafe
                        {
                            doc = processor.AnalyseLayoutBinaryImage(
                                binImage.BinaryData, greyImage.Width, greyImage.Height);
                        }
                        if (doc != null)
                        {
                            var bs = new List <string>();
                            if (doc.Blocks.Count > 0)
                            {
                                for (int i = 0; i < doc.Blocks.Count; i++)
                                {
                                    for (int j = 0; j < doc.Blocks[i].Paragraphs.Count; j++)
                                    {
                                        bs.AddRange(doc.Blocks[j].Paragraphs[j].Lines
                                                    .Select(x => string.Format(
                                                                "{0}_{1}_{2}_{3}", x.Left, x.Top, x.Right, x.Bottom)));
                                    }
                                }
                            }
                            req.output_format = "left_top_right_bottom";
                            req.output_text   = string.Join("|", bs.ToArray());
                            req.output_count  = bs.Count;
                            req.ok            = 1;
                        }
                        break;
                    }
                }
            }
        }

        return(req);
    }
        static void Simple2_Recognize()
        {
            int n_images = Images.Length;
            int i_image = n_images - 1;
            //i_image = 0;
            string fileName = Images[i_image];

            string imageFile = Path.Combine(InputFolder, fileName);

            string language = "eng";
            int oem = (int)eOcrEngineMode.OEM_DEFAULT;

            using (TesseractProcessor processor = new TesseractProcessor())
            {
                using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
                {
                    using (GreyImage greyImage = GreyImage.FromImage(bmp))
                    {

                        ImageThresholder thresholder = new AdaptiveThresholder();
                        using (BinaryImage binImage = thresholder.Threshold(greyImage))
                        {
                            DateTime started = DateTime.Now;
                            DateTime ended = DateTime.Now;

                            int i = 3;
                            //for (i = 0; i < 4; i++)
                            //for (i = 3; i < 4; i++)
                            {
                                oem = i;
                                processor.Init(TessdataFolder, language, oem);

                                string text = "";
                                unsafe
                                {
                                    started = DateTime.Now;

                                    text = processor.RecognizeBinaryImage(
                                        binImage.BinaryData, greyImage.Width, greyImage.Height);

                                    ended = DateTime.Now;

                                    Console.WriteLine("Duration recognition: {0} ms\n\n", (ended - started).TotalMilliseconds);
                                }

                                Console.WriteLine(
                                    string.Format("RecognizeMode: {1}\nRecognized Text:\n{0}\n++++++++++++++++++++++++++++++++\n", text, ((eOcrEngineMode)oem).ToString()));
                            }
                        }
                    }
                }
            }
        }
        public static void Recognize()
        {
            int n_images = Workspace.Images.Length;
            int i_image  = n_images - 1;

            i_image = 0;
            string fileName = Workspace.Images[i_image];

            string imageFile = Path.Combine(Workspace.InputFolder, fileName);

            string language = "eng";
            int    oem      = 3;

            TesseractProcessor processor = new TesseractProcessor();

            using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
            {
                GreyImage greyImage = GreyImage.FromImage(bmp);

                DateTime            started     = DateTime.Now;
                AdaptiveThresholder thresholder = new AdaptiveThresholder();
                BinaryImage         binImage    = thresholder.Threshold(greyImage);
                DateTime            ended       = DateTime.Now;
                Console.WriteLine("Duration thresholding: {0} ms", (ended - started).TotalMilliseconds);

                binImage.Invert();

                //for (int i = 0; i < 4; i++)
                for (int i = 3; i < 4; i++)
                {
                    oem = i;
                    oem = (int)eOcrEngineMode.OEM_TESSERACT_CUBE_COMBINED;
                    processor.Init(Workspace.TessdataFolder, language, oem);

                    string text = "";
                    unsafe
                    {
                        started = DateTime.Now;

                        //string text = processor.Recognize(bmp);
                        text = processor.RecognizeBinaryImage(
                            binImage.BinaryData, binImage.Width, binImage.Height);

                        ended = DateTime.Now;
                        Console.WriteLine("Duration recognition: {0} ms\n\n", (ended - started).TotalMilliseconds);
                    }

                    Console.WriteLine(
                        string.Format("RecognizeMode: {1}\nText:\n{0}\n++++++++++++++++++++++++++++++++\n", text, ((eOcrEngineMode)oem).ToString()));
                }
            }
        }
Example #15
0
 /// <summary>
 /// Применение морфологической операции открытия к контурному изображению
 /// </summary>
 /// <param name="image"></param>
 public override void Apply(GreyImage image)
 {
     try
     {
         if (image == null)
             throw new ArgumentNullException("Null image in Apply");
         this._erosion.Apply(image);
        // this._dilation.Apply(image);
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
 /// <summary>
 /// Бинаризация Отцу изображения
 /// </summary>
 /// <param name="image">Изображение</param>
 public void Binarize(GreyImage image)
 {
     try
     {
         if (image == null)
             throw new ArgumentNullException("Null image in Binarize");
         this.Treshold = Countreshold(image);
         SetColor(image);
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        /// <summary>
        /// Применение градиентного фильтра к изображению
        /// </summary>
        /// <param name="image">Изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");

                CountGradient(image);
                EnhanceGradientImage(image);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public override GreyImage Apply(GreyImage image, int threadsNumber)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (image.Height < this.Size)
                    throw new ArgumentException("Image height must be >= filter size");
                if (image.Width < this.Size)
                    throw new ArgumentException("Image width must be >= filter size");
                if (threadsNumber <= 0)
                    throw new ArgumentException("Error threadsNumber in Apply");

                this._copyImage = (GreyImage)image.Copy();
                if (this._copyImage == null)
                    throw new NullReferenceException("Null copy image in Apply");

                this.Threads = new List<Thread>();

                int deltaI = image.Height / threadsNumber;
                int lowIndex = 1;
                int lowIndexI = 1;
                int highIndexI = lowIndexI + deltaI;
                int highIndexJ = image.Width - 2;

                for (int i = 0; i < threadsNumber; i++)
                {
                    if (i == threadsNumber - 1)
                        highIndexI = image.Height - 2;

                    MatrixFilterData matrixFilterData = new ThreadData.MatrixFilterData(image, lowIndexI, highIndexI, lowIndex, highIndexJ);
                    Thread thread = new Thread(new ParameterizedThreadStart(this.ApplyThread));
                    this.Threads.Add(thread);
                    this.Threads[i].Start(matrixFilterData);

                    lowIndexI = highIndexI;
                    highIndexI += deltaI;
                }
                WaitForThreads();

                return this._copyImage;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        private void makeImg(int mxx, int myy, StartOfFrame frame)
        {
            if (frame.TypeOfImage == ImageType.GreyScale)
            {
                var m = new GreyImage(8 * mxx, 8 * myy);
                img1 = m.SubImage(0, 0, frame.Width, frame.Height);
            }
            else
            {
                var h0     = frame.Components[0].HorizontalSamplingFactor;
                var v0     = frame.Components[0].VerticalSamplingFactor;
                var hRatio = h0 / frame.Components[1].HorizontalSamplingFactor;
                var vRatio = v0 / frame.Components[1].VerticalSamplingFactor;

                var ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio444;
                switch ((hRatio << 4) | vRatio)
                {
                case 0x11:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio444;
                    break;

                case 0x12:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio440;
                    break;

                case 0x21:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio422;
                    break;

                case 0x22:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio420;
                    break;

                case 0x41:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio411;
                    break;

                case 0x42:
                    ratio = YCbCrSubsampleRatio.YCbCrSubsampleRatio410;
                    break;
                }

                var m = new YcbcrImg(8 * h0 * mxx, 8 * v0 * myy, ratio);
                img3 = m.SubImage(0, 0, frame.Width, frame.Height);
            }
        }
 /// <summary>
 /// Применение адаптивного фильтра Гаусса к серому изображению
 /// </summary>
 /// <param name="image">Серое изображение</param>
 public override void Apply(GreyImage image)
 {
     try
     {
         if (image == null)
             throw new ArgumentNullException("Null image in Apply");
         while (this.IterationsNumber > 0)
         {
             ProcessImage(image);
             --this.IterationsNumber;
         }
         this.IterationsNumber = DEFAULT_ITERATIONS_NUMBER;
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        /// <summary>
        /// Усиление градиентного изображения фильтром 3 на 3
        /// </summary>
        /// <param name="image">Градиентное изображение </param>
        private void EnhanceGradientImage(GreyImage image)
        {
            try
            {
                int imageHeight = image.Height - 1;
                int imageWidth = image.Width - 1;

                GreyImage copyImage = (GreyImage)image.Copy();

                for (int i = 1; i < imageHeight; i++)
                    for (int j = 1; j < imageWidth; j++)
                        image.Pixels[i, j].Color.Data = (byte) GetMaximumIntensityFromNeibours(copyImage, i, j);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Применение фильтра Лапласа к серому изображению
        /// </summary>
        /// <param name="image">Серое изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (image.Height < this.Size)
                    throw new ArgumentException("Image height must be >= filter size");
                if (image.Width < this.Size)
                    throw new ArgumentException("Image width must be >= filter size");

                GreyImage copyImage = (GreyImage)image.Copy();
                if (copyImage == null)
                    throw new NullReferenceException("Null copy image in Apply");

                int lowIndex = Size / 2;
                int highIndexI = image.Height - lowIndex;
                int highIndexJ = image.Width - lowIndex;
                for (int i = lowIndex; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        int gradientStrengthX = copyImage.Pixels[i - 1, j].Color.Data * Gx[0, 1] +
                          copyImage.Pixels[i, j - 1].Color.Data * Gx[1, 0] + copyImage.Pixels[i, j].Color.Data * Gx[1, 1] +
                          copyImage.Pixels[i, j + 1].Color.Data * Gx[1, 2] + copyImage.Pixels[i + 1, j].Color.Data * Gx[2, 1];

                        int gradientStrengthSqr = gradientStrengthX * gradientStrengthX + gradientStrengthX * gradientStrengthX;

                        if (gradientStrengthSqr > ColorBase.MAX_COLOR_VALUE)
                        {
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                            image.Pixels[i, j].BorderType = BorderType.Border.STRONG;
                        }
                        else
                        {
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;
                            image.Pixels[i, j].BorderType = BorderType.Border.WEAK;
                        }
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public void TestSobelFilter4()
        {
            //arrange
            EdgeDetectionFilter sobel = new SobelFilter();
            GreyImage image = new GreyImage(3, 3);

            image.Pixels[0, 0].Color.Data = 50;
            image.Pixels[0, 1].Color.Data = 125;
            image.Pixels[0, 2].Color.Data = 22;

            image.Pixels[1, 0].Color.Data = 12;
            image.Pixels[1, 1].Color.Data = 17;
            image.Pixels[1, 2].Color.Data = 187;

            image.Pixels[2, 0].Color.Data = 201;
            image.Pixels[2, 1].Color.Data = 100;
            image.Pixels[2, 2].Color.Data = 45;

            GreyImage patternImage = new GreyImage(3, 3);

            patternImage.Pixels[0, 0].Color.Data = 50;
            patternImage.Pixels[0, 1].Color.Data = 125;
            patternImage.Pixels[0, 2].Color.Data = 22;

            patternImage.Pixels[1, 0].Color.Data = 12;
            patternImage.Pixels[1, 1].Color.Data = (byte) ColorBase.MIN_COLOR_VALUE;
            patternImage.Pixels[1, 1].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;
            patternImage.Pixels[1, 2].Color.Data = 187;

            patternImage.Pixels[2, 0].Color.Data = 201;
            patternImage.Pixels[2, 1].Color.Data = 100;
            patternImage.Pixels[2, 2].Color.Data = 45;

            patternImage.Pixels[1, 1].Gradient.Angle = -36;
            patternImage.Pixels[1, 1].Gradient.Strength = 207;

            //act
            sobel.Apply(image);

            //assert
            Assert.IsTrue(image.IsEqual(patternImage));
        }
        /// <summary>
        /// Применение фильтра Гаусса к серому изображению
        /// </summary>
        /// <param name="image">Серое изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (image.Height < this.Size)
                    throw new ArgumentException("Image height must be >= filter size");
                if (image.Width < this.Size)
                    throw new ArgumentException("Image width must be >= filter size");

                GreyImage copyImage = (GreyImage) image.Copy();
                if (copyImage == null)
                    throw new NullReferenceException("Null copy image in Apply");

                int filterSize = this.Size;
                int lowIndex = filterSize / 2;
                int highIndexI = image.Height - lowIndex;
                int highIndexJ = image.Width - lowIndex;
                for (int i = lowIndex; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        int pixelColor = 0;
                        for (int k = 0; k < filterSize; k++)
                            for (int l = 0; l < filterSize; l++)
                                pixelColor += this.Kernel[k, l] * copyImage.Pixels[k + i - lowIndex, l + j - lowIndex].Color.Data;

                        pixelColor /= this.NormalizationRatio;
                        if (pixelColor > ColorBase.MAX_COLOR_VALUE)
                            pixelColor = ColorBase.MAX_COLOR_VALUE;
                        if (pixelColor < 0)
                            pixelColor = ColorBase.MIN_COLOR_VALUE;
                        image.Pixels[i, j].Color.Data = (byte) pixelColor;
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Example #25
0
        /// <summary>
        /// Применение морфологической операции эрозии к контурному изображению
        /// </summary>
        /// <param name="image"></param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");

                GreyImage copyImage = (GreyImage)image.Copy();

                int filterSize = this.Size;
                int lowIndex = filterSize / 2;
                int highIndexI = image.Height - 1;
                int highIndexJ = image.Width - lowIndex;
                for (int i = 1; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        if (copyImage.Pixels[i, j].Color.Data == ColorBase.MIN_COLOR_VALUE)
                        {
                            int pixelsNumber = 0;
                            for (int k = 0; k < filterSize; k++)
                                if (copyImage.Pixels[i, k + j - lowIndex].Color.Data == ColorBase.MIN_COLOR_VALUE)
                                    ++pixelsNumber;
                            if (pixelsNumber == filterSize)
                            {
                                for (int k = 0; k < lowIndex; k++)
                                    image.Pixels[i, k + j - lowIndex].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;

                                for (int k = lowIndex + 1; k < filterSize; k++)
                                    image.Pixels[i, k + j - lowIndex].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;
                                image.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                            }
                        }
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Вычисление градиентной карты по горизонтали и вертикали
        /// </summary>
        /// <param name="image">Изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");

                int imageHeight = image.Height - 1;
                int imageWidth = image.Width - 1;

                for (int i = 0; i < imageHeight; i++)
                    for (int j = 0; j < imageWidth; j++)
                    {
                        image.Pixels[i, j].Gradient.GradientX = image.Pixels[i, j].Color.Data - image.Pixels[i + 1, j].Color.Data;
                        image.Pixels[i, j].Gradient.GradientY = image.Pixels[i, j].Color.Data - image.Pixels[i, j + 1].Color.Data;
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Конвертация одното типа изображения в другое (переносится цвет)
        /// </summary>
        /// <param name="image">Изображение</param>
        /// <returns>Изображение</returns>
        public GreyImage ConvertColor(Image<Gray, byte> image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in ConvertColor");

                int imageHeight = image.Height;
                int imageWidth = image.Width;

                GreyImage newImage = new GreyImage(imageWidth, imageHeight);

                for (int i = 0; i < imageHeight; i++)
                    for (int j = 0; j < imageWidth; j++)
                        newImage.Pixels[i, j].Color.Data = image.Data[i, j, 0];
               return newImage;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public Bitmap ToBitmap(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in ToBitmap");

                int width = image.Width;
                int height = image.Height;
                Bitmap bitmap = new Bitmap(width, height);
                for (int i = 0; i < height; i++)
                    for (int j = 0; j < width; j++)
                    {
                        byte colorIntensity = image.Pixels[i, j].Color.Data;
                        bitmap.SetPixel(j, i, Color.FromArgb(colorIntensity, colorIntensity, colorIntensity));
                    }
                return bitmap;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Example #29
0
        /// <summary>
        /// Применение SWT фильтра к серому изображению
        /// </summary>
        /// <param name="image">Серое изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (image.Height != this._gaussSmoothedImage.Height || image.Width != this._gaussSmoothedImage.Width)
                    throw new ArgumentException("Image must be the same size with gaussSmoothedImage in ctor");
                this._maxIntensityDirectionImage = (GreyImage) image.Copy();
                if (this._maxIntensityDirectionImage == null)
                    throw new NullReferenceException("Null _minIntensityDirectionImage in Apply");
                this._minIntensityDirectionImage = (GreyImage)image.Copy();
                if (this._minIntensityDirectionImage == null)
                    throw new NullReferenceException("Null _minIntensityDirectionImage in Apply");

                FillMinIntensityImage(image);
                FillMaxIntensityImage(image);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Вычисление градиентной карты (многопоточная)
        /// </summary>
        /// <param name="image">Изображение</param>
        /// <param name="threadsNumber">Число потоков</param>
        /// <returns></returns>
        public override GreyImage Apply(GreyImage image, int threadsNumber)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (threadsNumber <= 0)
                    throw new ArgumentException("Error threadsNumber in Apply");

                this._gradientXMap = new GreyImage(image.Width, image.Height);
                this._gradientYMap = new GreyImage(image.Width, image.Height);

                this.Threads = new List<Thread>();
                int deltaI = image.Height / threadsNumber;
                int lowIndexI = 0;
                int highIndexI = lowIndexI + deltaI;

                for (int i = 0; i < threadsNumber; i++)
                {
                    if (i == threadsNumber - 1)
                        highIndexI = image.Height - 1;
                    MatrixFilterData matrixFilterData = new ThreadData.MatrixFilterData(image, lowIndexI, highIndexI, 0, image.Width - 1);
                    Thread thread = new Thread(new ParameterizedThreadStart(this.ApplyThread));
                    this.Threads.Add(thread);
                    this.Threads[i].Start(matrixFilterData);

                    lowIndexI = highIndexI;
                    highIndexI += deltaI;
                }
                WaitForThreads();
                return image;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
 public override GreyImage Apply(GreyImage image, int threadsNumber)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Применение фильтра Превитта к серому изображению
        /// </summary>
        /// <param name="image">Серое изображение</param>
        public override void Apply(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in Apply");
                if (image.Height < this.Size)
                    throw new ArgumentException("Image height must be >= filter size");
                if (image.Width < this.Size)
                    throw new ArgumentException("Image width must be >= filter size");

                GreyImage copyImage = (GreyImage)image.Copy();
                if (copyImage == null)
                    throw new NullReferenceException("Null copy image in Apply");

                int lowIndex = Size / 2;
                int highIndexI = image.Height - lowIndex;
                int highIndexJ = image.Width - lowIndex;
                for (int i = lowIndex; i < highIndexI; i++)
                    for (int j = lowIndex; j < highIndexJ; j++)
                    {
                        byte pixelI_1J_1 = copyImage.Pixels[i - 1, j - 1].Color.Data;
                        byte pixelI_1J1 = copyImage.Pixels[i - 1, j + 1].Color.Data;
                        byte pixelI1J1 = copyImage.Pixels[i + 1, j + 1].Color.Data;

                        int gradientStrengthY = pixelI_1J_1 * Gy[0, 0] +
                          copyImage.Pixels[i - 1, j].Color.Data * Gy[0, 1] + pixelI_1J1 * Gy[0, 2] +
                          copyImage.Pixels[i + 1, j - 1].Color.Data * Gy[2, 0] + copyImage.Pixels[i + 1, j].Color.Data * Gy[2, 1] +
                          pixelI1J1 * Gy[2, 2];

                        int gradientStrengthX = pixelI_1J_1 * Gx[0, 0] +
                          pixelI_1J1 * Gx[0, 2] + copyImage.Pixels[i, j - 1].Color.Data * Gx[1, 0] +
                          copyImage.Pixels[i, j + 1].Color.Data * Gx[1, 2] + copyImage.Pixels[i + 1, j - 1].Color.Data * Gx[2, 0] +
                          pixelI1J1 * Gx[2, 2];

                        int gradientStrengthSqr = gradientStrengthX * gradientStrengthX + gradientStrengthY * gradientStrengthY;
                        image.Pixels[i, j].Gradient.Strength = (int)Math.Sqrt((double)gradientStrengthSqr);

                        if (gradientStrengthSqr > TRESHOLD)
                        {
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                            image.Pixels[i, j].BorderType = BorderType.Border.STRONG;
                        }
                        else
                        {
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;
                            image.Pixels[i, j].BorderType = BorderType.Border.WEAK;
                        }

                        if (gradientStrengthX == 0)
                        {
                            if (gradientStrengthY == 0)
                                image.Pixels[i, j].Gradient.Angle = 0;
                            else
                                image.Pixels[i, j].Gradient.Angle = 90;
                        }
                        else
                            image.Pixels[i, j].Gradient.Angle = (int)((Math.Atan((double)gradientStrengthY / gradientStrengthX)) * (180 / Math.PI));
                    }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public void TestSobelFilter5()
        {
            //arrange
            EdgeDetectionFilter sobel = new SobelFilter();
            GreyImage image = new GreyImage(5, 4);

            image.Pixels[0, 0].Color.Data = 50;
            image.Pixels[0, 1].Color.Data = 125;
            image.Pixels[0, 2].Color.Data = 22;
            image.Pixels[0, 3].Color.Data = 11;
            image.Pixels[0, 4].Color.Data = 104;

            image.Pixels[1, 0].Color.Data = 12;
            image.Pixels[1, 1].Color.Data = 17;
            image.Pixels[1, 2].Color.Data = 187;
            image.Pixels[1, 3].Color.Data = 0;
            image.Pixels[1, 4].Color.Data = 15;

            image.Pixels[2, 0].Color.Data = 201;
            image.Pixels[2, 1].Color.Data = 100;
            image.Pixels[2, 2].Color.Data = 45;
            image.Pixels[2, 3].Color.Data = 91;
            image.Pixels[2, 4].Color.Data = 17;

            image.Pixels[3, 0].Color.Data = 100;
            image.Pixels[3, 1].Color.Data = 15;
            image.Pixels[3, 2].Color.Data = 18;
            image.Pixels[3, 3].Color.Data = 205;
            image.Pixels[3, 4].Color.Data = 194;

            GreyImage patternImage = new GreyImage(5, 4);

            patternImage.Pixels[0, 0].Color.Data = 50;
            patternImage.Pixels[0, 1].Color.Data = 125;
            patternImage.Pixels[0, 2].Color.Data = 22;
            patternImage.Pixels[0, 3].Color.Data = 11;
            patternImage.Pixels[0, 4].Color.Data = 104;

            patternImage.Pixels[1, 0].Color.Data = 12;
            patternImage.Pixels[1, 1].Color.Data = (byte) ColorBase.MIN_COLOR_VALUE;
            patternImage.Pixels[1, 2].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
            patternImage.Pixels[1, 3].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;

            patternImage.Pixels[1, 1].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;
            patternImage.Pixels[1, 2].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;
            patternImage.Pixels[1, 3].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;

            patternImage.Pixels[1, 4].Color.Data = 15;

            patternImage.Pixels[2, 0].Color.Data = 201;
            patternImage.Pixels[2, 1].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
            patternImage.Pixels[2, 2].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
            patternImage.Pixels[2, 3].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;

            patternImage.Pixels[2, 1].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;
            patternImage.Pixels[2, 2].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;
            patternImage.Pixels[2, 3].BorderType = DigitalImageProcessingLib.BorderType.Border.STRONG;

            patternImage.Pixels[2, 4].Color.Data = 17;

            patternImage.Pixels[3, 0].Color.Data = 100;
            patternImage.Pixels[3, 1].Color.Data = 15;
            patternImage.Pixels[3, 2].Color.Data = 18;
            patternImage.Pixels[3, 3].Color.Data = 205;
            patternImage.Pixels[3, 4].Color.Data = 194;

            patternImage.Pixels[1, 1].Gradient.Strength = 207;
            patternImage.Pixels[1, 1].Gradient.Angle = -36;

            patternImage.Pixels[1, 2].Gradient.Strength = 186;
            patternImage.Pixels[1, 2].Gradient.Angle = 32;

            patternImage.Pixels[1, 3].Gradient.Strength = 305;
            patternImage.Pixels[1, 3].Gradient.Angle = 18;

            patternImage.Pixels[2, 1].Gradient.Strength = 234;
            patternImage.Pixels[2, 1].Gradient.Angle = -21;

            patternImage.Pixels[2, 2].Gradient.Strength = 205;
            patternImage.Pixels[2, 2].Gradient.Angle = 41;

            patternImage.Pixels[2, 3].Gradient.Strength = 423;
            patternImage.Pixels[2, 3].Gradient.Angle = 82;

            //act
            image = sobel.Apply(image, 4);

            //assert
            Assert.IsTrue(image.IsEqual(patternImage));
        }
        static void Simple2_AnalyseLayout()
        {
            int n_images = Images.Length;
            int i_image = 0;
            for (; i_image < n_images; i_image++)
            {
                string fileName = Images[i_image];

                Console.WriteLine("{0} Image: {1}", i_image, fileName);

                string imageFile = Path.Combine(InputFolder, fileName);

                string name = Path.GetFileNameWithoutExtension(imageFile);

                string outFile = Path.Combine(OutputFolder, string.Format("Simple2_{0}_layout.bmp", name));
                string outFile2 = Path.Combine(OutputFolder, string.Format("Simple2_{0}_grey.bmp", name));
                string outFile3 = Path.Combine(OutputFolder, string.Format("Simple2_{0}_bin.bmp", name));

                using (TesseractProcessor processor = new TesseractProcessor())
                {
                    processor.InitForAnalysePage();
                    //processor.SetPageSegMode(ePageSegMode.PSM_AUTO);

                    using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
                    {
                        using (GreyImage greyImage = GreyImage.FromImage(bmp))
                        {
                            greyImage.Save(ImageFormat.Bmp, outFile2);

                            ImageThresholder thresholder = new AdaptiveThresholder();
                            using (BinaryImage binImage = thresholder.Threshold(greyImage))
                            {
                                binImage.Save(ImageFormat.Bmp, outFile3);

                                DateTime started = DateTime.Now;
                                DateTime ended = DateTime.Now;

                                DocumentLayout doc = null;

                                unsafe
                                {
                                    started = DateTime.Now;

                                    doc = processor.AnalyseLayoutBinaryImage(
                                        binImage.BinaryData, greyImage.Width, greyImage.Height);

                                    ended = DateTime.Now;

                                    Console.WriteLine("Duration AnalyseLayout: {0} ms", (ended - started).TotalMilliseconds);
                                }
                                Console.WriteLine(doc.ToString());

                                using (Image tmp = new Bitmap(bmp.Width, bmp.Height)) // prevents one-byte index format
                                {
                                    using (Graphics grph = Graphics.FromImage(tmp))
                                    {
                                        Rectangle rect = new Rectangle(0, 0, tmp.Width, tmp.Height);

                                        grph.DrawImage(bmp, rect, rect, GraphicsUnit.Pixel);

                                        grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                                        foreach (Block block in doc.Blocks)
                                        {
                                            Render.DrawBlock(grph, block);
                                        }
                                    }

                                    tmp.Save(outFile);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Выделение текста на изображении гибрибным подходом
        /// </summary>
        /// <param name="image">Изображение</param>
        public void DetectText(GreyImage image)
        {
            try
            {
                if (image == null)
                    throw new ArgumentNullException("Null image in DetectText");

               // textRegions = null;

                Thread edgeThread = new Thread(new ParameterizedThreadStart(this.EdgeBasedProcessThread));
                Thread gradientThread = new Thread(new ParameterizedThreadStart(this.GradientBasedProcessThread));

                GreyImage copyImage = (GreyImage)image.Copy();

                edgeThread.Start(copyImage);
                gradientThread.Start(copyImage);

                edgeThread.Join();
                gradientThread.Join();

                for (int i = 0; i < image.Height; i++)
                    for (int j = 0; j < image.Width; j++)
                    {
                        if (this._gradientImage.Pixels[i, j].Color.Data == ColorBase.MAX_COLOR_VALUE &&
                            this._edgeImage.Pixels[i, j].Color.Data == ColorBase.MIN_COLOR_VALUE)
                            copyImage.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                        else
                            copyImage.Pixels[i, j].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;

                        copyImage.Pixels[i, j].BorderType = this._edgeImage.Pixels[i, j].BorderType;
                      //  image.Pixels[i, j].Color.Data = this._gradientImage.Pixels[i, j].Color.Data;
                    }

                this._dilation.Apply(copyImage);

                int[] heightHist = new int[copyImage.Height];
                int[] widthHist = new int[copyImage.Width];

                for (int i = 0; i < copyImage.Height; i++)
                {
                    int sum = 0;
                    for (int j = 0; j < copyImage.Width; j++)
                    {
                        if (copyImage.Pixels[i, j].Color.Data == (byte)ColorBase.MIN_COLOR_VALUE)
                            ++sum;
                    }
                    heightHist[i] = sum;
                }

                int maxH = heightHist.Max();

                for (int i = 0; i < copyImage.Width; i++)
                {
                    int sum = 0;
                    for (int j = 0; j < copyImage.Height; j++)
                    {
                        if (copyImage.Pixels[j, i].Color.Data == (byte)ColorBase.MIN_COLOR_VALUE)
                            ++sum;
                    }
                    widthHist[i] = sum;
                }
                int maxw = widthHist.Max();

                for (int i = 0; i < heightHist.Length; i++)
                {
                    if (maxH - heightHist[i] < 150)
                        heightHist[i] = 1;
                    else
                        heightHist[i] = 0;
                }

                for (int i = 0; i < widthHist.Length; i++)
                {
                    if (maxw - widthHist[i] < 50)
                        widthHist[i] = 1;
                    else
                        widthHist[i] = 0;
                }

                for (int i = 0; i < image.Height; i++)
                {
                    for (int j = 0; j < image.Width; j++)
                    {
                        if (heightHist[i] == 1 && widthHist[j] == 1)
                            image.Pixels[i, j].Color.Data = (byte)ColorBase.MIN_COLOR_VALUE;
                     //   else
                           // image.Pixels[i, j].Color.Data = (byte)ColorBase.MAX_COLOR_VALUE;

                    }
                }

              //  this._opening.Apply(image);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// <summary>
        /// Процедура вычисления градиентного изображения
        /// </summary>
        /// <param name="data">Исходное изображение</param>
        private void GradientBasedProcessThread(object data)
        {
            try
            {
                GreyImage image = (GreyImage)data;
                this._gradientImage = (GreyImage)image.Copy();

                this._gradientFilter.Apply(this._gradientImage);
                this._binarizator.Binarize(this._gradientImage);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }