예제 #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);
            }
        }
예제 #2
0
        public void SetPixelTest(PixelFormat pixelFormat)
        {
            UnmanagedImage image = UnmanagedImage.Create(320, 240, pixelFormat);
            Color          color = Color.White;
            byte           value = 255;

            image.SetPixel(0, 0, color);
            image.SetPixel(319, 0, color);
            image.SetPixel(0, 239, color);
            image.SetPixel(319, 239, value);
            image.SetPixel(160, 120, value);

            image.SetPixel(-1, -1, color);
            image.SetPixel(320, 0, color);
            image.SetPixel(0, 240, value);
            image.SetPixel(320, 240, value);

            List <IntPoint> pixels = image.CollectActivePixels();

            Assert.AreEqual(5, pixels.Count);

            Assert.IsTrue(pixels.Contains(new IntPoint(0, 0)));
            Assert.IsTrue(pixels.Contains(new IntPoint(319, 0)));
            Assert.IsTrue(pixels.Contains(new IntPoint(0, 239)));
            Assert.IsTrue(pixels.Contains(new IntPoint(319, 239)));
            Assert.IsTrue(pixels.Contains(new IntPoint(160, 120)));
        }
예제 #3
0
        private void DrawVelocityMap(UnmanagedImage output)
        {
            Point sumVelocity = new Point();

            int indention = 7;
            int step      = 10;

            Invoke(() => step = VelocitiesDistanceTrackBar.Value);

            //Point[,] velocityField = ((dynamic)_tracker).CalculateVelocityField(_currentPreprocessedImage, _previousPreprocessedImage);

            for (int x = indention; x < _frameSize.Width - indention; x += step)
            {
                for (int y = indention; y < _frameSize.Height - indention; y += step)
                {
                    IntPoint p        = new IntPoint(x, y);
                    Point    velocity = _tracker.CalculateVelocity(_currentPreprocessedImage, _previousPreprocessedImage, p);
                    //Point velocity = velocityField[y, x];

                    sumVelocity += velocity;

                    if (velocity.EuclideanNorm() != 0.0f)
                    {
                        IntPoint newp = (p + velocity).Round();
                        Drawing.Line(output, p, newp, Color.White);
                        output.SetPixel(newp, Color.Red);
                    }
                }
            }

            Invoke(() => InfoLabel.Text = string.Format("Summary motion: ({0:+00.00;-00.00}; {1:+00.00;-00.00})", sumVelocity.X / 10, sumVelocity.Y / 10));
        }
예제 #4
0
 public void dessinePoint(IntPoint point, UnmanagedImage img, int nbPixel, Color col)
 {
     for (int i = point.X - nbPixel / 2; i < point.X + nbPixel / 2 + 1; i++)
     {
         for (int j = point.Y - nbPixel / 2; j < point.Y + nbPixel / 2 + 1; j++)
         {
             img.SetPixel(i, j, col);
         }
     }
 }
예제 #5
0
        /// <summary>
        /// Рисует вокруг ячейки рамку белого цвета
        /// </summary>
        public void Clear()
        {
            BitmapData imageData = _parentimage.LockBits(
                new Rectangle(0, 0, _parentimage.Width, _parentimage.Height),
                ImageLockMode.ReadWrite, _parentimage.PixelFormat);

            _image8 = new UnmanagedImage(imageData);
            for (int x = _rect.X; x <= _rect.Right; x++)
            {
                _image8.SetPixel(x, _rect.Y, 255);
                _image8.SetPixel(x, _rect.Bottom, 255);
            }
            for (int y = _rect.Y; y <= _rect.Bottom; y++)
            {
                _image8.SetPixel(_rect.X, y, 255);
                _image8.SetPixel(_rect.Right, y, 255);
            }

            _parentimage.UnlockBits(imageData);
        }
예제 #6
0
        private void SelectBlob(Blob _blob)
        {
            BitmapData imageData = _recogimg.LockBits(
                new Rectangle(0, 0, _image.Width, _recogimg.Height),
                ImageLockMode.ReadWrite, _recogimg.PixelFormat);

            UnmanagedImage _image8 = new UnmanagedImage(imageData);

            for (int x = _blob.Rectangle.X; x <= _blob.Rectangle.Right; x++)
            {
                _image8.SetPixel(x, _blob.Rectangle.Y, 0);
                _image8.SetPixel(x, _blob.Rectangle.Bottom, 0);
            }
            for (int y = _blob.Rectangle.Y; y <= _blob.Rectangle.Bottom; y++)
            {
                _image8.SetPixel(_blob.Rectangle.X, y, 0);
                _image8.SetPixel(_blob.Rectangle.Right, y, 0);
            }

            _recogimg.UnlockBits(imageData);
        }
예제 #7
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)));
                }
            }
        }
예제 #8
0
        public void SetPixelTestUnsupported(PixelFormat pixelFormat)
        {
            UnmanagedImage image = UnmanagedImage.Create(320, 240, pixelFormat);
            Color          color = Color.White;
            byte           value = 255;

            image.SetPixel(0, 0, color);
            image.SetPixel(319, 0, color);
            image.SetPixel(0, 239, color);
            image.SetPixel(319, 239, value);
            image.SetPixel(160, 120, value);

            image.SetPixel(-1, -1, color);
            image.SetPixel(320, 0, color);
            image.SetPixel(0, 240, value);
            image.SetPixel(320, 240, value);

            Assert.Throws <UnsupportedImageFormatException>(() => image.CollectActivePixels(), "");
        }
예제 #9
0
        public IntegralImageTest()
        {
            UnmanagedImage uImage = UnmanagedImage.Create(10, 10, PixelFormat.Format8bppIndexed);

            for (int y = 0; y < 10; y++)
            {
                for (int x = 0; x < 10; x++)
                {
                    uImage.SetPixel(x, y, ((x + y) % 2 == 0) ? Color.FromArgb(0, 0, 0) : Color.FromArgb(1, 1, 1));
                }
            }

            integralImage = IntegralImage.FromBitmap(uImage);
        }
예제 #10
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);
        }
예제 #11
0
파일: Program.cs 프로젝트: yart123/backsub
        public static Bitmap GetBitmap(this Color[,] colors)
        {
            Bitmap         bitmap = new Bitmap(colors.GetLength(0), colors.GetLength(1));
            BitmapInfo     info   = CreateBitmapInfo(bitmap);
            UnmanagedImage image  = info.Image;

            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    image.SetPixel(x, y, colors[x, y].ToDrawingColor());
                }
            }
            info.Bitmap.UnlockBits(info.Data);
            return(info.Bitmap);
        }
예제 #12
0
        /// <summary>
        /// Удаляет темный квадрат на расстоянии 5 пикселей от ячейки справа
        /// </summary>
        public void ClearRightMarker()
        {
            BitmapData imageData = _parentimage.LockBits(
                new Rectangle(0, 0, _parentimage.Width, _parentimage.Height),
                ImageLockMode.ReadWrite, _parentimage.PixelFormat);

            _image8 = new UnmanagedImage(imageData);
            for (int x = _rect.X + _rect.Width; x <= _rect.X + _rect.Width + 5; x++)
            {
                for (int y = _rect.Y; y <= _rect.Y + _rect.Height; y++)
                {
                    _image8.SetPixel(x, y, 255);
                }
            }

            _parentimage.UnlockBits(imageData);
        }
예제 #13
0
        public void ToManagedImageTest(PixelFormat pixelFormat, int x, int y, byte red, byte green, byte blue)
        {
            UnmanagedImage image = UnmanagedImage.Create(320, 240, pixelFormat);

            image.SetPixel(new IntPoint(x, y), Color.FromArgb(255, red, green, blue));

            Bitmap bitmap = image.ToManagedImage();

            // check colors of pixels
            Assert.AreEqual(Color.FromArgb(255, red, green, blue), bitmap.GetPixel(x, y));

            // make sure there are only 1 pixel
            UnmanagedImage temp = UnmanagedImage.FromManagedImage(bitmap);

            List <IntPoint> pixels = temp.CollectActivePixels();

            Assert.AreEqual(1, pixels.Count);

            image.Dispose();
            bitmap.Dispose();
            temp.Dispose();
        }
예제 #14
0
        public void Correct(UnmanagedImage img, double aFocalLinPixels, int limit, double scale, int offx, int offy)
        {
            if (Math.Abs(_aFocalLinPixels - aFocalLinPixels) > Double.Epsilon || limit != _mFeLimit ||
                Math.Abs(scale - _mScaleFeSize) > Double.Epsilon || img.Width != _w || img.Height != _h ||
                _offsetx != offx || _offsety != offy)
            {
                Init(aFocalLinPixels, limit, scale, img.Width, img.Height, offx, offy);
            }
            var correctImage = UnmanagedImage.Create(img.Width, img.Height, img.PixelFormat);

            img.Copy(correctImage);
            int c = 0;

            for (int x = 0; x < _w; x++)
            {
                for (int y = 0; y < _h; y++)
                {
                    img.SetPixel(x, y, correctImage.GetPixel(_map[c, 0], _map[c, 1]));
                    c++;
                }
            }
            correctImage.Dispose();
        }
예제 #15
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());
        }
예제 #16
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));
        }
예제 #17
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);
        }