예제 #1
0
        public void SetGetPixelColor(PixelFormat pixelFormat)
        {
            UnmanagedImage image = UnmanagedImage.Create(320, 240, pixelFormat);

            image.SetPixel(0, 0, Color.FromArgb(255, 10, 20, 30));
            image.SetPixel(319, 0, Color.FromArgb(127, 110, 120, 130));
            image.SetPixel(0, 239, Color.FromArgb(64, 210, 220, 230));

            Color color1 = image.GetPixel(0, 0);
            Color color2 = image.GetPixel(319, 0);
            Color color3 = image.GetPixel(0, 239);

            Assert.AreEqual(10, color1.R);
            Assert.AreEqual(20, color1.G);
            Assert.AreEqual(30, color1.B);

            Assert.AreEqual(110, color2.R);
            Assert.AreEqual(120, color2.G);
            Assert.AreEqual(130, color2.B);

            Assert.AreEqual(210, color3.R);
            Assert.AreEqual(220, color3.G);
            Assert.AreEqual(230, color3.B);

            if (pixelFormat == PixelFormat.Format32bppArgb)
            {
                Assert.AreEqual(255, color1.A);
                Assert.AreEqual(127, color2.A);
                Assert.AreEqual(64, color3.A);
            }
        }
        private bool isSame(UnmanagedImage img1, UnmanagedImage img2)
        {
            int   count = 0, tcount = img2.Width * img2.Height;
            int   c1a, c2a;
            Color c1, c2;

            for (int y = 0; y < img1.Height; y++)
            {
                for (int x = 0; x < img1.Width; x++)
                {
                    c1  = img1.GetPixel(x, y);
                    c2  = img2.GetPixel(x, y);
                    c1a = (c1.R + c1.G + c1.B) / 3;
                    c2a = (c2.R + c2.G + c2.B) / 3;

                    /* if ((c1.R + c1.G + c1.B) / 3 > (c2.R + c2.G + c2.B) / 3 - 10 &&
                     *   (c1.R + c1.G + c1.B) / 3 < (c2.R + c2.G + c2.B) / 3 + 10)*/
                    if (c1a > c2a - 10 && c1a < c2a + 10)
                    {
                        count++;
                    }
                }
            }
            return((count * 100) / tcount >= 54);
        }
예제 #3
0
        public Boolean[,] Recognize(IntPoint corners, UnmanagedImage img)
        {
            /* Retourne une matrice représentant le glyph*/

            int      moyenne;
            IntPoint ip    = new IntPoint();
            int      marge = (imgGlyph.Width * 5) / 100;

            // Calucul de la taille des cellules
            int cellWidth  = (imgGlyph.Width - marge) / glyphSize;
            int cellHeight = (imgGlyph.Height - marge) / glyphSize;

            // Définition d'une matrice contenant les valeurs de l'image
            Boolean[,] cellIntensity = new Boolean[glyphSize, glyphSize];


            // Découpage du glyph en zone
            for (int i = 0; i < glyphSize; i++)
            {
                for (int j = 0; j < glyphSize; j++)
                {
                    moyenne = 0;
                    int count = 0;

                    for (int x = (marge + cellWidth * i + 1); x < (marge + cellWidth * (i + 1) - 2); x += 2)
                    {
                        for (int y = (marge + cellHeight * j + 1); y < (marge + cellHeight * (1 + j) - 2); y += 2)
                        {
                            ip.X = x;
                            ip.Y = y;
                            count++;

                            moyenne += imgGlyph.GetPixel(ip).R;
                        }
                    }
                    cellIntensity[i, j] = (moyenne / count > 127) ? false : true;
                }
            }

            // Debug

            /*{
             *  string chaine;
             *  Logger.GlobalLogger.debug("");
             *  Logger.GlobalLogger.debug("Nouvelle analyse");
             *  Logger.GlobalLogger.debug("");
             *  for (int gi = 0; gi < glyphSize; gi++)
             *  {
             *      chaine = "";
             *      for (int gj = 0; gj < glyphSize; gj++)
             *      {
             *          chaine += cellIntensity[gi, gj] + "\t";
             *      }
             *      Logger.GlobalLogger.debug(chaine);
             *  }
             *
             * }
             */
            return(cellIntensity);
        }
예제 #4
0
 public int[,] GetMatrix(UnmanagedImage unmanagedImage)
 {
     int[,] matrix = new int[unmanagedImage.Width, unmanagedImage.Height];
     for (int x = 0; x < unmanagedImage.Width; x++)
     {
         for (int y = 0; y < unmanagedImage.Height; y++)
         {
             matrix[x, y] = (int)unmanagedImage.GetPixel(x, y).R;
         }
     }
     return(matrix);
 }
예제 #5
0
        public static void ForEachPixel(this UnmanagedImage image, Func <Color, Color> modify)
        {
            var w = image.Width;
            var h = image.Height;

            for (var y = 0; y < h; y++)
            {
                for (var x = 0; x < w; x++)
                {
                    image.SetPixel(x, y, modify(image.GetPixel(x, y)));
                }
            }
        }
예제 #6
0
        public static void ForEachPixel(this UnmanagedImage image, Action <int, Color> generate)
        {
            var w = image.Width;
            var h = image.Height;

            for (var y = 0; y < h; y++)
            {
                var offset = y * w;
                for (var x = 0; x < w; x++)
                {
                    generate(offset + x, image.GetPixel(x, y));
                }
            }
        }
예제 #7
0
파일: OMR.cs 프로젝트: Assim/e-marker
        private long InkDarkness(Bitmap OMark)
        {
            int darkestC = 255, lightestC = 0;

            UnmanagedImage mark = UnmanagedImage.FromManagedImage(OMark);

            for (int y = 0; y < OMark.Height; y++)
            {
                for (int x = 0; x < OMark.Width; x++)
                {
                    Color c = mark.GetPixel(x, y);
                    if (((c.R + c.G + c.B) / 3) > lightestC)
                    {
                        lightestC = ((c.R + c.G + c.B) / 3);
                    }
                    if (((c.R + c.G + c.B) / 3) < darkestC)
                    {
                        darkestC = ((c.R + c.G + c.B) / 3);
                    }
                }
            }
            int dc = 0;

            for (int y = 0; y < OMark.Height; y++)
            {
                for (int x = 0; x < OMark.Width; x++)
                {
                    Color c = mark.GetPixel(x, y);

                    if (((c.R + c.G + c.B) / 3) < (lightestC + darkestC) / 2)
                    {
                        dc += 255;
                    }
                }
            }
            return(dc);
        }
예제 #8
0
        public long InkDarkness(Bitmap OMark) //get the darkness of each circle area
        {
            int darkestC = 255, lightestC = 0;

            UnmanagedImage mark = UnmanagedImage.FromManagedImage(OMark); //image in unmanaged memory

            for (int y = 0; y < OMark.Height; y++)
            {
                for (int x = 0; x < OMark.Width; x++)
                {
                    Color c = mark.GetPixel(x, y);
                    if (((c.R + c.G + c.B) / 3) > lightestC)
                    {
                        lightestC = ((c.R + c.G + c.B) / 3);
                    }
                    if (((c.R + c.G + c.B) / 3) < darkestC)
                    {
                        darkestC = ((c.R + c.G + c.B) / 3);
                    }
                }
            }
            int dc = 0;

            for (int y = 0; y < OMark.Height; y++)
            {
                for (int x = 0; x < OMark.Width; x++)
                {
                    Color c = mark.GetPixel(x, y);

                    if (((c.R + c.G + c.B) / 3) < (lightestC + darkestC) / 2)
                    {
                        dc += 255;
                    }
                }
            }
            return(dc);
        }
예제 #9
0
        public void SetGetPixelGrayscale()
        {
            UnmanagedImage image = UnmanagedImage.Create(320, 240, PixelFormat.Format8bppIndexed);

            image.SetPixel(0, 0, 255);
            image.SetPixel(319, 0, 127);
            image.SetPixel(0, 239, Color.FromArgb(64, 64, 64));

            Color color1 = image.GetPixel(0, 0);
            Color color2 = image.GetPixel(319, 0);
            Color color3 = image.GetPixel(0, 239);

            Assert.AreEqual(255, color1.R);
            Assert.AreEqual(255, color1.G);
            Assert.AreEqual(255, color1.B);

            Assert.AreEqual(127, color2.R);
            Assert.AreEqual(127, color2.G);
            Assert.AreEqual(127, color2.B);

            Assert.AreEqual(64, color3.R);
            Assert.AreEqual(64, color3.G);
            Assert.AreEqual(64, color3.B);
        }
예제 #10
0
        public double[] Preprocess(Bitmap bmp)
        {
            int w = bmp.Width;
            int h = bmp.Height;

            System.Drawing.Imaging.BitmapData imdata = bmp.LockBits(
                new Rectangle(0, 0, w, h),
                System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);

            UnmanagedImage unmImg = new UnmanagedImage(imdata);


            double[] res = new double[w * h];
            for (int i = 0; i < w; ++i)
            {
                for (int j = 0; j < h; ++j)
                {
                    float c = unmImg.GetPixel(i, j).GetBrightness();
                    res[i * w + j] = c;
//                    Color c = bmp.GetPixel(i, j);

                    /*if (c.R < 50 && c.G < 50 && c.B < 50)
                     *  res[i * w + j] = 1;
                     * else res[i * w + j] = 0;*/
                }
            }

            bmp.UnlockBits(imdata);

            return(res);

            /*Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
             * System.Drawing.Imaging.BitmapData bmpData =
             *  bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
             *  bmp.PixelFormat);
             *
             * // Get the address of the first line.
             * IntPtr ptr = bmpData.Scan0;
             *
             * // Declare an array to hold the bytes of the bitmap.
             * int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
             * double[] res = new double[bytes];
             *
             * // Copy the RGB values into the array.
             * System.Runtime.InteropServices.Marshal.Copy(ptr, res, 0, bytes);
             *
             * return res;*/
        }
예제 #11
0
        public static bool IsSameAs(this UnmanagedImage imageToBeCompared, UnmanagedImage referenceImage)
        {
            Grayscale gsf = new Grayscale(0.2989, 0.5870, 0.1140);

            imageToBeCompared = gsf.Apply(imageToBeCompared);
            referenceImage    = gsf.Apply(referenceImage);

            Bitmap bmp1 = imageToBeCompared.ToManagedImage(), bmp2 = referenceImage.ToManagedImage();

            int count = 0, tcount = referenceImage.Width * referenceImage.Height;

            for (int y = 0; y < imageToBeCompared.Height; y++)
            {
                for (int x = 0; x < imageToBeCompared.Width; x++)
                {
                    Color c1 = imageToBeCompared.GetPixel(x, y), c2 = referenceImage.GetPixel(x, y);

                    int a1 = (c1.R + c1.G + c1.B) / 3;
                    int a2 = (c2.R + c2.G + c2.B) / 3;

                    if ((a1 < 127) == (a2 < 127))
                    {
                        if (a2 > 127)
                        {
                            count++;
                        }
                        else
                        {
                            tcount--;
                        }
                    }
                    else
                    {
                        count--;
                    }
                }
            }

            count += tcount;
            count /= 2;

            bool returnValue = (count * 100) / tcount >= 50;


            return(returnValue);
        }
예제 #12
0
        private bool isSame(UnmanagedImage img1, UnmanagedImage img2)
        {
            int count = 0, tcount = img2.Width * img2.Height;

            for (int y = 0; y < img1.Height; y++)
            {
                for (int x = 0; x < img1.Width; x++)
                {
                    Color c1 = img1.GetPixel(x, y), c2 = img2.GetPixel(x, y);
                    if ((c1.R + c1.G + c1.B) / 3 > (c2.R + c2.G + c2.B) / 3 - 10 &&
                        (c1.R + c1.G + c1.B) / 3 < (c2.R + c2.G + c2.B) / 3 + 10)
                    {
                        count++;
                    }
                }
            }
            return((count * 100) / tcount >= 54);
        }
        private void GetBitmapColorMatix(Bitmap b1)
        {
            // create grayscale filter(BT709)
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);

            // apply the filter
            System.Drawing.Bitmap grayImage = filter.Apply(b1);

            pictureBoxGray.Image = grayImage;
            unmanagedImage       = UnmanagedImage.FromManagedImage(grayImage);


            matrix = new int[unmanagedImage.Width, unmanagedImage.Height];
            for (int x = 0; x < unmanagedImage.Width; x++)
            {
                for (int y = 0; y < unmanagedImage.Height; y++)
                {
                    matrix[x, y] = (int)unmanagedImage.GetPixel(x, y).R;
                }
            }
        }
예제 #14
0
        private static RGB _GetAverageColor(Bitmap bitmap)
        {
            using (UnmanagedImage bmp = UnmanagedImage.FromManagedImage(bitmap))
            {
                Color  tempColor;
                double r = 0, g = 0, b = 0;
                for (int i = 0; i < bmp.Height; i++)
                {
                    for (int j = 0; j < bmp.Width; j++)
                    {
                        tempColor = bmp.GetPixel(j, i);
                        r        += tempColor.R;
                        g        += tempColor.G;
                        b        += tempColor.B;
                    }
                }
                int scale = bmp.Height * bmp.Width;
                r /= scale;
                g /= scale;
                b /= scale;

                return(new RGB((byte)r, (byte)g, (byte)b));
            }
        }
예제 #15
0
        private UnmanagedImage FindTargets(UnmanagedImage image)
        {
            AForge.Point centerPoint = new AForge.Point(image.Width / 2, image.Height / 2);

            List <AForge.Point> targets = new List <AForge.Point>();

            unsafe
            {
                for (int y = 0; y < image.Height; y++)
                {
                    for (int x = 0; x < image.Width; x++)
                    {
                        Color pixel = image.GetPixel(x, y);

                        //if (Math.Abs(x - centerPoint.X) < 80 && Math.Abs(y - centerPoint.Y) < 30)
                        {
                            bool isTarget = (pixel.R != 0 || pixel.G != 0 || pixel.B != 0);
                            if (isTarget)
                            {
                                targets.Add(new AForge.Point(x, y));
                            }
                            else
                            {
                                image.SetPixel(x, y, Color.White);
                            }
                            //row[x * PixelSize + 0] = 255;
                            //row[x * PixelSize + 1] = 255;
                            //row[x * PixelSize + 2] = 255;
                        }
                    }
                }
            }

            if (targets.Count > 0)
            {
                int          xBox           = 3;
                int          yBox           = 3;
                AForge.Point medianOfMedian = new AForge.Point();

                //LOL
                List <AForge.Point> medians = TargetDetector.GetMedianOfTargets(targets);
                foreach (AForge.Point p in medians)
                {
                    //Calculate Hit Box
                    medianOfMedian.X += p.X;
                    medianOfMedian.Y += p.Y;

                    for (int x = Math.Max((int)p.X - xBox, 0); x < Math.Min((int)p.X + xBox, image.Width); x++)
                    {
                        for (int y = Math.Max((int)p.Y - yBox, 0); y < Math.Min((int)p.Y + yBox, image.Height); y++)
                        {
                            image.SetPixel(x, y, Color.Plum);
                        }
                    }

                    for (int x = (int)centerPoint.X - xBox; x < (int)centerPoint.X + xBox; x++)
                    {
                        for (int y = (int)centerPoint.Y - yBox; y < (int)centerPoint.Y + yBox; y++)
                        {
                            //image.SetPixel(x, y, Color.GreenYellow);
                        }
                    }
                }

                medianOfMedian.X = medianOfMedian.X / medians.Count;
                medianOfMedian.Y = medianOfMedian.Y / medians.Count;

                for (int x = (int)medianOfMedian.X - xBox; x < (int)medianOfMedian.X + xBox; x++)
                {
                    for (int y = (int)medianOfMedian.Y - yBox; y < (int)medianOfMedian.Y + yBox; y++)
                    {
                        image.SetPixel(x, y, Color.Red);
                    }
                }



                int moveX = (int)((medianOfMedian.X - centerPoint.X) * 1);
                int moveY = (int)((medianOfMedian.Y - centerPoint.Y) * 1);
                //sim.Mouse.MoveMouseBy((int)((medianX - centerX) * ratioX), (int)((medianY - centerY) * ratioY));

                if (isOn)
                {
                    Console.WriteLine("Targets: " + medians.Count);
                    //double ratioWidth = screenShot.HorizontalResolution / img.HorizontalResolution;
                    //double ratioHeight = screenShot.VerticalResolution / img.VerticalResolution;
                    Mouse.FreezeMouse();
                    AimHard(moveX / 2, moveY / 2);
                    Mouse.ThawMouse();
                    //Console.WriteLine("Move: " + moveX + ", " + moveY);
                    //AimSmooth(moveX, moveY);
                    //Console.WriteLine("Targets: " + medians.Count);
                }


                return(image);
            }

            return(image);
        }
예제 #16
0
        public Dictionary <string, int> CropImgae(BitmapData cloneBitmapCopyCSource, Bitmap btSource, UnmanagedImage sourceimageSource, int h0, String nameFile)
        {
            BitmapData     cloneBitmapCopyC = cloneBitmapCopyCSource;
            Bitmap         bt          = btSource;
            UnmanagedImage sourceimage = sourceimageSource;

            Color c;
            //Tìm x trái nhất
            int k, xt1, yt1, xt2, yt2, space, h, d, heighd, xt1min, xt2max, dong, tmp1, tmp2, tmp, hd, kc, weight, heightpage;

            tmp1 = tmp2 = k = h = dong = xt1min = xt2max = heighd = d = space = xt1 = yt1 = xt2 = yt2 = tmp = kc = weight = heightpage = 0;
            if (nameFile.Contains("NoiNhanCV"))
            {
                weight = sourceimage.Width;
            }
            else
            {
                weight = (int)(0.9 * sourceimage.Width / 2);
            }
            heightpage = sourceimage.Height;
            for (hd = h0; hd <= h0 + 20; hd++)
            {
                for (k = 0; k < weight; k++)
                {
                    c = sourceimage.GetPixel(k, hd);
                    if (c.R == 0)
                    {
                        xt1 = k;
                        break;
                    }
                }
                if (tmp == 0 || tmp > xt1)
                {
                    tmp = xt1;
                    yt1 = hd;
                }
            }

            xt1 = tmp;
            tmp = 0;
            d   = yt1;
            for (k = xt1; k < weight; k++)
            {
                for (h = d; h < (h0 + 59); h++)
                {
                    if (space > 2000)
                    {
                        break;
                    }

                    c = sourceimage.GetPixel(k, h);
                    if (c.R == 0)
                    {
                        xt2 = k;
                        yt2 = h;
                        if (tmp == 0 || tmp < yt2)
                        {
                            tmp = yt2;
                        }

                        space = 0;
                    }
                    else if (c.R == 255)
                    {
                        space += 1;
                    }
                }
            }
            yt2 = tmp;
            int height = 0;

            tmp = 0;
            if (nameFile.Contains("donviSoanCV") || nameFile.Contains("TieuDeCV"))
            {
                if (nameFile.Contains("donviSoanCV"))
                {
                    heighd = height = yt2 + (int)(0.12 * yt2);
                    kc     = yt2;
                }
                else if (nameFile.Contains("TieuDeCV"))
                {
                    heighd = height = (yt2 - yt1) + (int)(0.2 * (yt2 - yt1));
                    if (h0 > 250)
                    {
                        kc = yt2 - yt1 + (int)(0.5 * (yt2 - yt1));
                    }
                    else
                    {
                        kc = yt2 - yt1;
                    }
                    yt1 = yt1 - (int)(0.3 * (yt2 - yt1));
                    xt1 = 0;
                }

                dong = 1;
                do
                {
                    for (hd = height; hd <= (height + dong * ((int)(0.65 * yt2))); hd++)
                    {
                        h = 0;
                        d = 0;
                        for (k = 0; k < weight; k++)
                        {
                            c = sourceimage.GetPixel(k, hd);
                            if (c.R == 0)
                            {
                                if (h == 0)
                                {
                                    xt1min = k;
                                    if (tmp == 0 || tmp > xt1min)
                                    {
                                        tmp = xt1min;
                                    }
                                    h++;
                                }
                                else
                                {
                                    xt2max = k;
                                }

                                d++;
                            }
                        }
                    }
                    xt1min = tmp;
                    if (dong == 1)
                    {
                        tmp1 = xt1;
                        tmp2 = xt2;
                    }
                    if (d > 0)
                    {
                        if (tmp1 > xt1min)
                        {
                            tmp1 = xt1min;
                        }
                        if (tmp2 < xt2max)
                        {
                            tmp2 = xt2max;
                        }
                        dong++;
                    }
                } while (d > 0);

                if (dong > 1)
                {
                    if (tmp1 < xt1)
                    {
                        xt1 = tmp1;
                    }
                    if (tmp2 > xt2)
                    {
                        xt2 = tmp2;
                    }
                    height = height + dong * kc + (int)(0.2 * kc);
                }
            }
            else
            {
                heighd = height = (yt2 - yt1) + (int)(0.2 * (yt2 - yt1));
                yt1    = yt1 - (int)(0.5 * (yt2 - yt1));
            }

            if (nameFile.Contains("donviSoanCV"))
            {
                cloneBitmapCopyC = bt.LockBits(new System.Drawing.Rectangle(xt1, 0, xt2 - xt1, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
            }
            else
            {
                cloneBitmapCopyC = bt.LockBits(new System.Drawing.Rectangle(xt1, yt1, xt2 - xt1, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
            }

            UnmanagedImage titileImage = new UnmanagedImage(cloneBitmapCopyC);
            Bitmap         imgTitile   = titileImage.ToManagedImage();
            String         filePath    = rootPath + nameFile + ".bmp";

            if (!System.IO.File.Exists(filePath))
            {
                FileStream output_title = new FileStream((rootPath + nameFile + ".bmp"), FileMode.Create);
                imgTitile.Save(output_title, System.Drawing.Imaging.ImageFormat.Jpeg);
                output_title.Dispose();
                output_title.Close();
            }
            bt.UnlockBits(cloneBitmapCopyC);
            Dictionary <string, int> dictionaryheight = new Dictionary <string, int>();

            dictionaryheight.Add("height", height);
            dictionaryheight.Add("heighd", heighd);
            return(dictionaryheight);
        }
예제 #17
0
        public ActionResult Upload(HttpPostedFileBase file)
        {
            string path = Server.MapPath("~/Areas/Admin/Files/" + file.FileName);
            string ext  = System.IO.Path.GetExtension(file.FileName);

            string[] nameFielCV = file.FileName.Split('.');
            if (String.Compare(ext.ToLower(), "pdf") == 0)
            {
                @ViewBag.Path = "Bạn chỉ có thể tải lên file PDF";
            }
            else
            {
                file.SaveAs(path);
                @ViewBag.Path = path;
                //@ViewBag.Path = "Test"+ExtractTextFromPdf(path);
                Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(path);

                int pageNum = pdfDoc.Pages.Count;
                // Response.Write("Hello--" + pageNum);
                XImage[] image = new XImage[pageNum];

                String NoiSoanCV, SoCV, TieuDeCV, NoiDungCV, NoiNhanCV, ChuKyCV, filePath;
                NoiSoanCV = SoCV = TieuDeCV = NoiDungCV = NoiNhanCV = ChuKyCV = filePath = "";
                Color c;
                for (int i = 1; i <= pageNum; i++)
                {
                    Bitmap         bt;
                    UnmanagedImage sourceimage;
                    BitmapData     cloneBitmapCopyC;
                    filePath = rootPath + file.FileName + nameFielCV[0] + i + ".bmp";
                    if (!System.IO.File.Exists(filePath))
                    {
                        using (FileStream imageStream = new FileStream(rootPath + nameFielCV[0] + i + ".bmp", FileMode.Create))
                        {
                            // Create Resolution object
                            Resolution resolution = new Resolution(300);
                            // Create JPEG device with specified attributes (Width, Height, Resolution, Quality)
                            // where Quality [0-100], 100 is Maximum
                            JpegDevice jpegDevice = new JpegDevice(resolution, 100);

                            // Convert a particular page and save the image to stream
                            jpegDevice.Process(pdfDoc.Pages[i], imageStream);
                            // Close stream
                            imageStream.Close();
                        }
                        // Thao tác với bt
                        bt = (Bitmap)Bitmap.FromFile((rootPath + nameFielCV[0] + i + ".bmp"));
                        bt.SetResolution(192f, 192f);
                        cloneBitmapCopyC = bt.LockBits(new System.Drawing.Rectangle(0, 114, bt.Width, bt.Height - 114), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
                        sourceimage      = new UnmanagedImage(cloneBitmapCopyC);

                        // chuyển thành ảnh cấp xám xong Nhi Phan (Đen thành đen , Trắng Thành Trắng)
                        for (int m = 0; m < sourceimage.Width; m++)
                        {
                            for (int j = 0; j < sourceimage.Height; j++)
                            {
                                c = sourceimage.GetPixel(m, j);
                                //c.R = 0; // màu đen
                                int grayScale = (int)((c.R * 0.3) + (c.G * 0.59) + (c.B * 0.11));
                                sourceimage.SetPixel(m, j, Color.FromArgb(c.A, grayScale, grayScale, grayScale));
                                if (c.R < 140)
                                {
                                    sourceimage.SetPixel(m, j, Color.Black);
                                }
                                else
                                {
                                    sourceimage.SetPixel(m, j, Color.White);
                                }
                            }
                        }
                        bt       = sourceimage.ToManagedImage();
                        bt       = Crop(bt);
                        filePath = rootPath + nameFielCV[0] + "output_grayCV" + i + ".bmp";
                        if (!System.IO.File.Exists(filePath))
                        {
                            FileStream output_gray = new FileStream((rootPath + nameFielCV[0] + "output_grayCV" + i + ".bmp"), FileMode.Create);
                            bt.Save(output_gray, System.Drawing.Imaging.ImageFormat.Jpeg);
                            output_gray.Dispose();
                            output_gray.Close();
                        }
                    }
                    else
                    {
                        // Thao tác với bt
                        bt = (Bitmap)Bitmap.FromFile((rootPath + nameFielCV[0] + "output_grayCV" + i + ".bmp"));
                        cloneBitmapCopyC = bt.LockBits(new System.Drawing.Rectangle(0, 0, bt.Width, bt.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
                        sourceimage      = new UnmanagedImage(cloneBitmapCopyC);
                    }

                    sourceimage = UnmanagedImage.FromManagedImage(bt);

                    String nameFile = "";
                    if (i == 1)
                    {
                        int ht, hs;
                        ht = hs = 0;

                        //Cắt tiêu đề
                        nameFile = nameFielCV[0] + "donviSoanCV";
                        Dictionary <string, int> dictionaryheightDV = CropImgae(cloneBitmapCopyC, bt, sourceimage, ht, nameFile);
                        ht = dictionaryheightDV["height"] + (int)1.3 * dictionaryheightDV["heighd"];
                        Bitmap dvCV = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        NoiSoanCV = GetText(dvCV);

                        //cắt số công văn
                        nameFile = nameFielCV[0] + "soCV";
                        Dictionary <string, int> dictionaryheightSoCV = CropImgae(cloneBitmapCopyC, bt, sourceimage, ht, nameFile);
                        ht = ht + dictionaryheightSoCV["height"];
                        Bitmap soCV = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        SoCV = GetText(soCV);

                        //cắt tiêu đề công văn
                        nameFile = nameFielCV[0] + "TieuDeCV";
                        Dictionary <string, int> dictionaryheightTieuDeCV = CropImgae(cloneBitmapCopyC, bt, sourceimage, ht, nameFile);
                        Bitmap TieuDeCVBit = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        ht = ht + dictionaryheightTieuDeCV["height"];
                        if (ht > 460)
                        {
                            ht = ht + (int)(2 * dictionaryheightTieuDeCV["heighd"]);
                        }
                        TieuDeCV = GetText(TieuDeCVBit);

                        //cắt nội dung
                        nameFile = nameFielCV[0] + "NoiDungCV";
                        BitmapData cloneBitmapNoiDungCV = bt.LockBits(new System.Drawing.Rectangle(0, ht, sourceimage.Width, sourceimage.Height - ht), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);

                        UnmanagedImage titileImage = new UnmanagedImage(cloneBitmapNoiDungCV);
                        Bitmap         imgTitile   = titileImage.ToManagedImage();
                        filePath = rootPath + nameFile + ".bmp";
                        if (!System.IO.File.Exists(filePath))
                        {
                            FileStream output_title = new FileStream((rootPath + nameFile + ".bmp"), FileMode.Create);
                            imgTitile.Save(output_title, System.Drawing.Imaging.ImageFormat.Jpeg);
                            output_title.Dispose();
                            output_title.Close();
                        }
                        Bitmap NoiDungCVBit = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        NoiDungCV = GetText(NoiDungCVBit);
                    }
                    if (i == pageNum)
                    {
                        //cắt nơi nhận, chữ ký
                        bool kt = false;
                        for (int k = (int)(0.98 * bt.Height); k < bt.Height; k++)
                        {
                            c = sourceimage.GetPixel((int)(0.5 * bt.Width), k);
                            if (c.R == 0)
                            {
                                kt = true; break;
                            }
                        }
                        if (kt)
                        {
                            BitmapData cloneBitmapPageEnd = bt.LockBits(new System.Drawing.Rectangle(0, 0, bt.Width, bt.Height - 114), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
                            sourceimage = new UnmanagedImage(cloneBitmapPageEnd);
                            bt          = sourceimage.ToManagedImage();
                            bt          = Crop(bt);
                            nameFile    = nameFielCV[0] + "PageEndCV";
                            filePath    = rootPath + nameFile + ".bmp";
                            if (!System.IO.File.Exists(filePath))
                            {
                                FileStream PageEndCV = new FileStream((rootPath + nameFile + ".bmp"), FileMode.Create);
                                bt.Save(PageEndCV, System.Drawing.Imaging.ImageFormat.Jpeg);
                                PageEndCV.Dispose();
                                PageEndCV.Close();
                            }
                            sourceimage = UnmanagedImage.FromManagedImage(bt);
                            //bt.UnlockBits(cloneBitmapPageEnd);
                        }

                        //cắt chữ ký
                        nameFile = nameFielCV[0] + "ChuKyCV";
                        BitmapData cloneBitmapChuKyCV = bt.LockBits(new System.Drawing.Rectangle((int)(0.5 * sourceimage.Width), (int)(0.9 * sourceimage.Height), (int)(0.4 * sourceimage.Width), sourceimage.Height - (int)(0.9 * sourceimage.Height)), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);

                        UnmanagedImage ChuKyImage  = new UnmanagedImage(cloneBitmapChuKyCV);
                        Bitmap         ChuKyTitile = ChuKyImage.ToManagedImage();
                        ChuKyTitile = Crop(ChuKyTitile);
                        filePath    = rootPath + nameFile + ".bmp";
                        if (!System.IO.File.Exists(filePath))
                        {
                            FileStream output_ChuKy = new FileStream((rootPath + nameFile + ".bmp"), FileMode.Create, FileAccess.ReadWrite);
                            ChuKyTitile.Save(output_ChuKy, System.Drawing.Imaging.ImageFormat.Jpeg);
                            output_ChuKy.Dispose();
                            output_ChuKy.Close();
                        }

                        bt.UnlockBits(cloneBitmapChuKyCV);
                        Bitmap ChuKyCVBit = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        ChuKyCV = GetText(ChuKyCVBit);

                        // cắt nơi nhận

                        nameFile = nameFielCV[0] + "NoiNhanCV";
                        BitmapData cloneBitmapNoiNhanCV;
                        if (!kt)
                        {
                            cloneBitmapNoiNhanCV = bt.LockBits(new System.Drawing.Rectangle(0, (int)(0.8 * (sourceimage.Height)), (int)(0.5 * sourceimage.Width), sourceimage.Height - (int)(0.8 * sourceimage.Height) - 50), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
                        }
                        else
                        {
                            cloneBitmapNoiNhanCV = bt.LockBits(new System.Drawing.Rectangle(0, (int)(0.6 * (sourceimage.Height - 10)), (int)(0.5 * sourceimage.Width), sourceimage.Height - (int)(0.6 * sourceimage.Height) - 50), System.Drawing.Imaging.ImageLockMode.ReadWrite, bt.PixelFormat);
                        }

                        UnmanagedImage NoiNhanImage  = new UnmanagedImage(cloneBitmapNoiNhanCV);
                        Bitmap         NoiNhanTitile = NoiNhanImage.ToManagedImage();
                        NoiNhanTitile = Crop(NoiNhanTitile);
                        filePath      = rootPath + nameFile + ".bmp";
                        if (!System.IO.File.Exists(filePath))
                        {
                            FileStream output_NoiNhan = new FileStream((rootPath + nameFile + ".bmp"), FileMode.Create);
                            NoiNhanTitile.Save(output_NoiNhan, System.Drawing.Imaging.ImageFormat.Jpeg);
                            output_NoiNhan.Dispose();
                            output_NoiNhan.Close();
                        }

                        Bitmap NoiNhanCVBit = (Bitmap)Bitmap.FromFile((rootPath + nameFile + ".bmp"));
                        NoiNhanCV = GetText(NoiNhanCVBit);
                        bt.UnlockBits(cloneBitmapChuKyCV);
                    }
                }
                //Lưu thông tin vừa cắt vào cơ sở dữ liệu
                row data = new row();
                //NoiSoanCV, SoCV, TieuDeCV, NoiDungCV, NoiNhanCV, ChuKyCV;
                data.from_org        = NoiSoanCV;
                data.number_dispatch = SoCV;
                data.title           = TieuDeCV;
                data._abstract       = NoiDungCV;
                data.to_org          = NoiNhanCV;
                data.name_signer     = ChuKyCV;
                data.attach_file     = file.FileName;
                try
                {
                    db.rows.Add(data);
                    db.SaveChanges();

                    return(RedirectToAction("List", "CongVan"));
                }
                catch (Exception e)
                {
                    string x = e.InnerException.ToString();
                    return(RedirectToAction("Index"));
                }
            }

            return(View());
        }
예제 #18
0
        //eventhandler if new frame is ready
        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = (Bitmap)eventArgs.Frame.Clone();

            if (counterImg == 10)
            {
                double delaisImage = DateTime.Now.TimeOfDay.TotalMilliseconds - _mill_last_pic;
                _mill_last_pic = DateTime.Now.TimeOfDay.TotalMilliseconds;

                double FPS = 1 / delaisImage * 1000 * counterImg + 1;
                // txt_nb_fps.Text = FPS.ToString() ;


                //txt_resolution.Text = "" + videoSource.DesiredFrameSize.Height + " * " + videoSource.DesiredFrameSize.Width;
                string resolutionTxt = "" + img.Width + " * " + img.Height;
                if (this != null && (!this.IsDisposed))
                {
                    try
                    {
                        this.Invoke((ProcessNewFPS)UpdateNewFPS, FPS);
                        this.Invoke((ProcessNewResolution)UpdateNewResolution, resolutionTxt);
                    }
                    catch (ObjectDisposedException) // La fenetre était en train de se fermée
                    {
                    }
                }
                counterImg = 0;
            }
            counterImg++;

            //Rectangle rect = new Rectangle(0,0,eventArgs.Frame.Width,eventArgs.Frame.Height);



            // 1 - grayscaling
            UnmanagedImage image      = UnmanagedImage.FromManagedImage(img);
            UnmanagedImage imageRouge = image.Clone();
            UnmanagedImage imageBleu  = image.Clone();
            UnmanagedImage imageVert  = image.Clone();
            UnmanagedImage grayImage  = null;

            Color colorPoint = image.GetPixel(posX, posY);

            this.Invoke((ProcessLalbelText)ChangeLabelText, new object[] { colorPoint.GetHue().ToString(), lbl_hue });
            this.Invoke((ProcessLalbelText)ChangeLabelText, new object[] { colorPoint.GetBrightness().ToString(), lbl_lum });
            this.Invoke((ProcessLalbelText)ChangeLabelText, new object[] { colorPoint.GetSaturation().ToString(), lbl_sat });

            if (image.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                grayImage = image;
            }
            else
            {
                grayImage = UnmanagedImage.Create(image.Width, image.Height,
                                                  PixelFormat.Format8bppIndexed);
                Grayscale.CommonAlgorithms.BT709.Apply(image, grayImage);
            }

            // 2 - Edge detection
            DifferenceEdgeDetector edgeDetector = new DifferenceEdgeDetector();
            UnmanagedImage         edgesImage   = edgeDetector.Apply(grayImage);

            // 3 - Threshold edges
            Threshold thresholdFilterGlyph   = new Threshold((short)numericUpDown3.Value);
            Threshold thresholdFilterCouleur = new Threshold((short)numericUpDown2.Value);

            thresholdFilterGlyph.ApplyInPlace(edgesImage);

            /*
             *
             * Bitmap image = (Bitmap)eventArgs.Frame.Clone();
             *
             * //Reference : http://www.aforgenet.com/framework/docs/html/743311a9-6c27-972d-39d2-ddc383dd1dd4.htm
             *
             *  private HSLFiltering filter = new HSLFiltering();
             * // set color ranges to keep red-orange
             * filter.Hue = new IntRange(0, 20);
             * filter.Saturation = new DoubleRange(0.5, 1);
             *
             * // apply the filter
             * filter.ApplyInPlace(image);
             * */
            /*RGB colorRed = new RGB(215, 30, 30);
             * RGB colorBlue = new RGB(10, 10, 215);
             * RGB colorVert = new RGB(30, 215, 30);
             * RGB colorBlanc = new RGB(225, 219, 160);*/

            HSLFiltering filter = new HSLFiltering();

            // create filter
            // EuclideanColorFiltering filter = new EuclideanColorFiltering();
            //filter.Radius = (short)numericUpDown1.Value;
            filter.Hue        = new IntRange(40, 140);
            filter.Saturation = new Range(0.5f, 1.0f);
            filter.Luminance  = new Range(0.2f, 1.0f);

            //filter.CenterColor = colorRed;
            filter.ApplyInPlace(imageRouge);

            filter.Hue = new IntRange(100, 180);
            //filter.CenterColor = colorBlanc;
            filter.ApplyInPlace(imageVert);

            filter.Hue = new IntRange(0, 40);
            //filter.CenterColor = colorBlue;
            filter.ApplyInPlace(imageBleu);



            Grayscale filterRouge = new Grayscale(0.800, 0.200, 0.200);
            Grayscale filterVert  = new Grayscale(0.200, 0.800, 0.200);
            Grayscale filterBleu  = new Grayscale(0.200, 0.200, 0.800);

            UnmanagedImage grayRougeImage = filterRouge.Apply(imageRouge);
            UnmanagedImage grayBleuImage  = filterBleu.Apply(imageBleu);


            UnmanagedImage edgesRougeImage = edgeDetector.Apply(grayRougeImage);
            UnmanagedImage edgesBleuImage  = edgeDetector.Apply(grayBleuImage);

            thresholdFilterCouleur.ApplyInPlace(edgesRougeImage);
            thresholdFilterCouleur.ApplyInPlace(edgesBleuImage);
            // All the image processing is done here...

            // pictureBox1.Image = image.ToManagedImage();
            if (this != null && (!this.IsDisposed)) // Si on est pas en train de suppirmer la fenetre
            {
                try
                {
                    this.Invoke((ProcessNewImage)DisplayNewImage, new object[] { image, pic_ImageNormal });
                    this.Invoke((ProcessNewImage)DisplayNewImage, new object[] { edgesImage, pic_ImageEdge });

                    this.Invoke((ProcessNewImage)DisplayNewImage, new object[] { imageRouge, pic_ImageRouge });

                    this.Invoke((ProcessNewImage)DisplayNewImage, new object[] { imageBleu, pic_ImageBleu });
                    this.Invoke((ProcessNewImage)DisplayNewImage, new object[] { imageVert, pic_ImageVert });
                }
                catch (ObjectDisposedException) // La fenetre était en train de se fermée
                {
                }
            }

            /*pictureBox2.Image = grayImage.ToManagedImage();
             * pictureBox3.Image = edgesImage.ToManagedImage();
             * pictureBox4.Image = imageRouge.ToManagedImage();*/
        }
예제 #19
0
        /// <summary>
        /// Hàm kế thừa từ thư viện AForge.NET.
        /// Là hàm chính của bộ lọc.
        /// </summary>
        /// <param name="sourceData">Ảnh nguồn đầu vào</param>
        /// <param name="destinationData">Ảnh đầu ra thể hiện các đoạn sau khi được chia. Các đoạn được tô màu ngẫu nhiên</param>
        protected override void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData)
        {
            // Có thể cần làm mượt ảnh trước khi tiến hành phân đoạn
            // sourceData = new GaussianBlur().Apply(sourceData);

            // Ở đây chúng ta dùng Color LAB để so sánh độ tương đồng của 2 màu khác nhau trong không gian màu RGB
            // Link tham khảo:
            // +: http://colormine.org/delta-e-calculator/
            // +: http://zschuessler.github.io/DeltaE/learn/
            // Sử dụng lớp so sánh từ thư viện ColorMine

            _logger.Log(string.Format("Ảnh đầu vào: {0}x{1}", sourceData.Width, sourceData.Height));
            _logger.Log(string.Format("Tham số: Threshold {0}, Minsize {1}", threshold, minsize));

            // Xây dựng đồ thị từ hình ảnh
            // Mỗi đỉnh đồ thị là 1 điểm ảnh,
            // Các đỉnh lân cận sẽ có cạnh nối với nhau và
            // có trọng số là <độ chênh lệnh> giữa 2 điểm ảnh đó
            // Ở đây sử dụng 4 liền kề
            // Kết quả sẽ có (Width-1)*(Height-1)*2 cạnh của đồ thị
            _logger.Log("Bắt đầu phrase 1 -  phân hoạch hình ảnh");
            var comp      = new CieDe2000Comparison();
            var items     = new QueueItem[(sourceData.Width - 1) * (sourceData.Height - 1) * 2];
            var itemCount = 0;

            for (var y = 0; y < sourceData.Height - 1; y++)
            {
                for (var x = 0; x < sourceData.Width - 1; x++)
                {
                    var color = sourceData.GetPixel(x, y).ToColorMine();
                    items[itemCount++] = new QueueItem(color.Compare(sourceData.GetPixel(x + 1, y).ToColorMine(), comp),
                                                       new Point(x, y), new Point(x + 1, y));
                    items[itemCount++] = new QueueItem(color.Compare(sourceData.GetPixel(x, y + 1).ToColorMine(), comp),
                                                       new Point(x, y), new Point(x, y + 1));
                }
            }

            // Xây dựng hàng chờ bao gồm các cạnh sắp xếp theo thứ tự
            // Trọng số không giảm
            // Bắt đầu tiến hành tìm cây khung nhỏ nhất (Minimum spanning tree) bằng thuật toán Krusal.
            _logger.Log(string.Format("Hàng chờ hiện có {0} đối tượng", itemCount));
            Array.Sort(items, new QueueItemComparer());
            var set = new DisjointSet(sourceData.Width, sourceData.Height);

            for (var i = 0; i < itemCount; i++)
            {
                if (items[i].Val > threshold)
                {
                    break;
                }
                set.Join(items[i].U, items[i].V);
            }
            _logger.Log(string.Format("Phrase 1 đã xong, đã tìm thấy {0} đoạn", set.NumSet));

            // Tiết hành sát nhập các vùng nhỏ hơn "minSize" với nhau
            // Cho chất lượng ảnh đầu ra tốt hơn
            _logger.Log(string.Format("Bắt đầu phrase 2, kết hợp các vùng nhỏ lại"));
            for (var y = 0; y < sourceData.Height - 1; y++)
            {
                for (var x = 0; x < sourceData.Width - 1; x++)
                {
                    var current = set.Parent(new Point(x, y));
                    int a = set.Parent(new Point(x + 1, y)), b = set.Parent(new Point(x, y + 1));
                    if (current != a && (set.SizeOf(current) < minsize || set.SizeOf(a) < minsize))
                    {
                        set.Join(current, a);
                    }
                    if (current != b && (set.SizeOf(current) < minsize || set.SizeOf(b) < minsize))
                    {
                        set.Join(current, b);
                    }
                }
            }
            _logger.Log(string.Format("Phrase 2 đã xong, đã tìm thấy {0} đoạn", set.NumSet));

            // Bảng màu tô màu các đoạn (super pixels) đã tìm được
            _logger.Log(string.Format("Bắt đầu tô màu các đoạn"));
            var colorDict = new Dictionary <int, Color>();

            for (var y = 0; y < sourceData.Height; y++)
            {
                for (var x = 0; x < sourceData.Width; x++)
                {
                    var   p = set.Parent(new Point(x, y));
                    Color cl;
                    if (!colorDict.ContainsKey(p))
                    {
                        cl           = RandomColor();
                        colorDict[p] = cl;
                    }
                    else
                    {
                        cl = colorDict[p];
                    }
                    destinationData.SetPixel(x, y, cl);
                }
            }
            _logger.Log(string.Format("Phân hoạch ảnh xong"));
            _logger.Log(new string('-', 80));
        }