コード例 #1
0
        private void ilvImages_ItemDoubleClick(object sender, ItemClickEventArgs e)
        {
            int currentImageIndex  = ilvImages.SelectedItems[0].Index;
            int modifiedImageIndex = 0;
            int halfRange          = 100;
            int startIndex         = Math.Max(currentImageIndex - halfRange, 0);
            int endIndex           = Math.Min(startIndex + (halfRange * 2) + 1, ilvImages.Items.Count);

            List <string> filteredImages = new List <string>();

            for (int i = startIndex; i < endIndex; i++)
            {
                string imageFilePath = ilvImages.Items[i].FileName;

                if (i == currentImageIndex)
                {
                    modifiedImageIndex = filteredImages.Count;
                }

                filteredImages.Add(imageFilePath);
            }

            ImageViewer.ShowImage(filteredImages.ToArray(), modifiedImageIndex);
        }
コード例 #2
0
        private void rotationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (img == null) // verify if the image is already opened
            {
                return;
            }

            InputBox form = new InputBox("rotate");

            form.ShowDialog();
            double rot = Convert.ToInt64(form.textBoxBright.Text);

            Cursor = Cursors.WaitCursor; // clock cursor

            imgUndo = img.Copy();
            ImageClass.Rotation(img, imgUndo, rot);
            //copy Undo Image


            ImageViewer.Image = img.Bitmap;
            ImageViewer.Refresh();    // refresh image on the screen

            Cursor = Cursors.Default; // normal cursor
        }
コード例 #3
0
        public static void Main()
        {
            using (Mat sourceImage = CvInvoke.Imread("../../../characters/characters-and-clues-result.jpg"))
            {
                //Mat scaledImage = new Mat();
                //CvInvoke.Resize(sourceImage, scaledImage, Size.Empty, 1.5, 1.5);

                List <Rectangle> detectedRectangles = DetectSquares(sourceImage)
                                                      .ToList();

                Image <Bgr, byte> destinationImage = sourceImage.ToImage <Bgr, byte>();

                //destinationImage.Draw(detectedRectangles[15], new Bgr(Color.DarkOrange), 2);
                //destinationImage.Draw(detectedRectangles[16], new Bgr(Color.DarkOrange), 2);

                //foreach (Rectangle rectangle in detectedRectangles)
                //{
                //    destinationImage.Draw(rectangle, new Bgr(Color.DarkOrange), 1);
                //}

                ImageViewer.Show(destinationImage);
                destinationImage.Save("../../../characters/characters-and-clues-result-two.jpg");
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: virzak/emgucv
        static void Run()
        {
            IInputOutputArray image;

            //Read the files as an 8-bit Bgr image

            image = new UMat("lena.jpg", ImreadModes.Color); //UMat version
            //image = new Mat("lena.jpg", ImreadModes.Color); //CPU version

            long             detectionTime;
            List <Rectangle> faces = new List <Rectangle>();
            List <Rectangle> eyes  = new List <Rectangle>();

            DetectFace.Detect(
                image, "haarcascade_frontalface_default.xml", "haarcascade_eye.xml",
                faces, eyes,
                out detectionTime);

            foreach (Rectangle face in faces)
            {
                CvInvoke.Rectangle(image, face, new Bgr(Color.Red).MCvScalar, 2);
            }
            foreach (Rectangle eye in eyes)
            {
                CvInvoke.Rectangle(image, eye, new Bgr(Color.Blue).MCvScalar, 2);
            }

            //display the image
            using (InputArray iaImage = image.GetInputArray())
                ImageViewer.Show(image, String.Format(
                                     "Completed face and eye detection using {0} in {1} milliseconds",
                                     (iaImage.Kind == InputArray.Type.CudaGpuMat && CudaInvoke.HasCuda) ? "CUDA" :
                                     (iaImage.IsUMat && CvInvoke.UseOpenCL) ? "OpenCL"
            : "CPU",
                                     detectionTime));
        }
コード例 #5
0
        /// <summary>
        /// Any setting that is derived from the homepage html needs to be in this function.  This function is turned
        /// on and off when detecting blog settings through the IncludeHomePageSettings.  None of these checks will be run
        /// if the internet is not active.  As each check is made, it does not need to be applied back the _content until the end
        /// at which time it will write the settings back to the registry.
        /// </summary>
        private void DetectHomePageSettings()
        {
            if (_homepageAccessor.HtmlDocument == null)
            {
                return;
            }

            IDictionary homepageSettings = new Hashtable();

            Debug.Assert(!UseManifestCache, "This code will not run correctly under the manifest cache, due to option overrides not being set");

            LightWeightHTMLMetaData metaData = new LightWeightHTMLMetaData(_homepageAccessor.HtmlDocument);

            if (metaData.Charset != null)
            {
                try
                {
                    homepageSettings.Add(BlogClientOptions.CHARACTER_SET, metaData.Charset);
                }
                catch (NotSupportedException)
                {
                    //not an actual encoding
                }
            }

            string docType = new LightWeightHTMLMetaData(_homepageAccessor.HtmlDocument).DocType;

            if (docType != null)
            {
                bool xhtml = docType.IndexOf("xhtml", StringComparison.OrdinalIgnoreCase) >= 0;
                if (xhtml)
                {
                    homepageSettings.Add(BlogClientOptions.REQUIRES_XHTML, true.ToString(CultureInfo.InvariantCulture));
                }
            }

            //checking whether blog is rtl
            HtmlExtractor extractor = new HtmlExtractor(_homepageAccessor.HtmlDocument.RawHtml);

            if (extractor.Seek(new OrPredicate(
                                   new SmartPredicate("<html dir>"),
                                   new SmartPredicate("<body dir>"))).Success)
            {
                BeginTag tag = (BeginTag)extractor.Element;
                string   dir = tag.GetAttributeValue("dir");
                if (String.Compare(dir, "rtl", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    homepageSettings.Add(BlogClientOptions.TEMPLATE_IS_RTL, true.ToString(CultureInfo.InvariantCulture));
                }
            }

            if (_homepageAccessor.HtmlDocument != null)
            {
                string      html   = _homepageAccessor.OriginalHtml;
                ImageViewer viewer = DhtmlImageViewers.DetectImageViewer(html, _context.HomepageUrl);
                if (viewer != null)
                {
                    homepageSettings.Add(BlogClientOptions.DHTML_IMAGE_VIEWER, viewer.Name);
                }
            }

            _context.HomePageOverrides = homepageSettings;
        }
コード例 #6
0
ファイル: MainForm.cs プロジェクト: szymani/Signs_Recognition
        private void Identify1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (img == null) // verify if the image is already opened
            {
                return;
            }
            Cursor = Cursors.WaitCursor; // clock cursor

            //copy Undo Image
            imgUndo     = img.Copy();
            imgOriginal = img.Copy();

            List <Image <Bgr, Byte> > triangles = new List <Image <Bgr, Byte> >();

            for (int i = 0; i < 9; i++)
            {
                triangles.Add(new Image <Bgr, Byte>("..\\..\\Imagens-20190916\\signs\\" + i + ".png"));
            }

            //List of detected signs
            List <string[]> signs = new List <string[]>();

            //Classification results (list for each object)
            List <int> classification = new List <int>();

            //List for evaluation
            List <string[]> limitSign       = new List <string[]>();
            List <string[]> warningSign     = new List <string[]>();
            List <string[]> prohibitionSign = new List <string[]>();

            //HSV image inside imgUndo, you can change imgUndo to imgHsv to get different result (also Bgr to Hsv change needed in BgrToHsv func)
            Identify.BgrToHsv(img, imgUndo);
            List <List <int[]> > allObject     = Identify.connectedComponents(imgUndo, img);
            List <int[]>         signsObjects  = allObject[0];
            List <int[]>         numberObjects = allObject[1];

            foreach (int[] number in numberObjects)
            {
                //Scale digits image
                digits = Identify.Scale(digits, number);

                triangles = Identify.Scale(triangles, number);

                //Thresholding detected sector
                Identify.ConvertToBW_Otsu_coords(imgOriginal, number);

                //Identify digit
                classification.Add(Identify.DetectDigit(imgOriginal, digits, number));
            }

            //Creating final output of detected signs
            //signs = Identify.CreateFinalList(classification, signsObjects, numberObjects);

            foreach (string[] sign in signs)
            {
                if (sign[0].Equals("-1"))
                {
                    if (!Identify.DetectTriangle(img, triangles, new int[] { Int32.Parse(sign[1]), Int32.Parse(sign[2]), Int32.Parse(sign[3]), Int32.Parse(sign[4]) }, 0.7).Equals(-1))
                    {
                        warningSign.Add(sign);
                    }
                    else
                    {
                        prohibitionSign.Add(sign);
                    }
                }
                else
                {
                    limitSign.Add(sign);
                }
            }

            ImageClass.Signs(img, imgUndo, out limitSign, out warningSign, out prohibitionSign, 2);
            //ImageViewer.Image = imgHsv.Bitmap;
            ImageViewer.Image = img.Bitmap;

            ImageViewer.Refresh();    // refresh image on the screen
            Cursor = Cursors.Default; // normal cursor
        }
コード例 #7
0
        private void TexturesList_DoubleClick(object sender, EventArgs e)
        {
            if (texturesList.Items.Count == 0)
            {
                return;
            }

            string ext = Path.GetExtension(texturesList.GetItemText(texturesList.SelectedItem));

            string[] exts        = { ".bti", ".tpl", ".bclim" };
            bool     isSupported = false;

            for (int i = 0; i < exts.Length; i++)
            {
                if (exts[i] == ext)
                {
                    isSupported = true;
                    break;
                }
            }

            if (!isSupported)
            {
                MessageBox.Show("This image format does not support viewing yet.");
                return;
            }

            string fullPath = mMainRoot + "timg/" + texturesList.GetItemText(texturesList.SelectedItem);

            byte[] data = null;

            if (mLayoutImages.ContainsKey(fullPath))
            {
                data = mLayoutImages[fullPath];
            }

            // this is because TEX1 has paths as upper but the filenames are lowercase
            if (data == null)
            {
                if (mLayoutImages.ContainsKey(fullPath.ToLower()))
                {
                    data = mLayoutImages[fullPath.ToLower()];
                }
            }

            if (data == null)
            {
                return;
            }

            EndianBinaryReader reader = new EndianBinaryReader(data);

            ImageContainerBase container = null;

            // no need for a default case since it will return if the format isnt supported
            switch (ext)
            {
            case ".tpl":
                container = new TPL(ref reader);
                break;

            case ".bti":
                container = new BTI(ref reader);
                break;

            case ".bclim":
                container = new BCLIM(ref reader);
                break;
            }

            if (container == null)
            {
                return;
            }

            ImageViewer viewer = new ImageViewer(texturesList.GetItemText(texturesList.SelectedItem));

            viewer.setImage(container.getImage(0));
            viewer.Show();
        }
コード例 #8
0
        //Draw Rectangle Iterative
        private void digitsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (img == null) // verify if the image is already opened
            {
                return;
            }


            //copy Undo Image
            imgUndo = img.Copy();
            //imgCopia = img.Copy();



            Cursor = Cursors.WaitCursor; // clock cursor
            float angleRad = 0;
            int   angle    = 6;

            int[] matrix = new int[4];  //[xf,xi,yf,yi]
            angleRad = (float)(Math.PI / 180) * angle;
            float treshold = 5;


            ImageClass.ConvertToBW_Otsu(img);
            ImageClass.Negative(img);
            imgCopia = img.Copy();
            ImageClass.Rotation(img, imgCopia, angleRad);
            imgCopia = img.Copy();
            ImageClass.Border(img);
            imgCopia = img.Copy();
            matrix   = ImageClass.RectangleIterative(img, treshold);

            //[xf,xi,yf,yi]
            Point bc_centroid1 = new Point(0, 0);

            bc_centroid1.X = matrix[1]; //(matrix[0] - matrix[1])/2;
            bc_centroid1.Y = matrix[3]; //(matrix[2] - matrix[3])/2;


            Size bc_size1 = new Size(0, 0);

            bc_size1.Width  = Math.Abs((matrix[0] - matrix[1]));
            bc_size1.Height = Math.Abs((matrix[2] - matrix[3]));

            string bc_image1  = "ola";
            string bc_number1 = "ola";

            Point bc_centroid2 = new Point(0, 0);

            bc_centroid2.X = 0;
            bc_centroid2.Y = 0;

            Size bc_size2 = new Size(0, 0);

            bc_size2.Width  = 0;
            bc_size2.Height = 0;

            string bc_image2  = "ola";
            string bc_number2 = "ola";


            ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);


            //ImageClass.BarCodeReader(img, 0, out Point1, new Size (190,71), "imagem", "number", new Point(95, 36), new Size(190, 71), "imagem2", "number2");

            ImageViewer.Image = img.Bitmap;
            ImageViewer.Refresh();    // refresh image on the screen

            Cursor = Cursors.Default; // normal cursor
        }
コード例 #9
0
        private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo info)
        {
            if (info != null)
            {
                string filePath = info.FilePath;

                switch (clickAction)
                {
                case ThumbnailViewClickAction.Default:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                    {
                        if (Helpers.IsImageFile(filePath))
                        {
                            pbThumbnail.Enabled = false;

                            try
                            {
                                ImageViewer.ShowImage(filePath);
                            }
                            finally
                            {
                                pbThumbnail.Enabled = true;
                            }
                        }
                        else if (Helpers.IsTextFile(filePath) || Helpers.IsVideoFile(filePath) || MessageBox.Show("Would you like to open this file?" + "\r\n\r\n" + filePath,
                                                                                                                  Resources.ShareXConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            Helpers.OpenFile(filePath);
                        }
                    }
                    break;

                case ThumbnailViewClickAction.OpenImageViewer:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && Helpers.IsImageFile(filePath))
                    {
                        pbThumbnail.Enabled = false;

                        try
                        {
                            ImageViewer.ShowImage(filePath);
                        }
                        finally
                        {
                            pbThumbnail.Enabled = true;
                        }
                    }
                    break;

                case ThumbnailViewClickAction.OpenFile:
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        Helpers.OpenFile(filePath);
                    }
                    break;

                case ThumbnailViewClickAction.OpenFolder:
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        Helpers.OpenFolderWithFile(filePath);
                    }
                    break;

                case ThumbnailViewClickAction.OpenURL:
                    if (info.Result != null)
                    {
                        URLHelpers.OpenURL(info.Result.ToString());
                    }
                    break;

                case ThumbnailViewClickAction.EditImage:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && Helpers.IsImageFile(filePath))
                    {
                        TaskHelpers.AnnotateImageFromFile(filePath);
                    }
                    break;
                }
            }
        }
コード例 #10
0
 public void SetViewer(ImageViewer viewer)
 {
     _panViewer.ImageViewer = viewer;
 }
コード例 #11
0
ファイル: ImageViewer.cs プロジェクト: hitswa/winforms
	public static void Main(String[] args)
	{
		ImageViewer form = new ImageViewer();
		Application.Run(form);
	}
コード例 #12
0
ファイル: Theme.cs プロジェクト: h3tch/ProtoFX
 private static bool ApplyTo(ImageViewer c)
 {
     c.BackColor = Workspace;
     c.ForeColor = ForeColor;
     return false;
 }
コード例 #13
0
		private void InitImageContainer()
		{
			_imageContainer = new ImageViewer();
			Controls.Add(_imageContainer);
			_imageContainer.Dock = DockStyle.Fill;
			var menuItemCopy = new System.Windows.Forms.MenuItem("Copy to Clipboard");
			menuItemCopy.Click += Copy_Click;
			_imageContainer.ContextMenu = new System.Windows.Forms.ContextMenu(new[] { menuItemCopy });
		}
コード例 #14
0
        private void service_DragDelta(object sender, InteractiveDragDeltaEventArgs e)
        {
            if (!IsWorking)
            {
                return;
            }

            var       imageViewer             = this.ImageViewer;
            bool      controlPointsHasChanged = false;
            LeadRectD itemBounds = ImageViewer.GetItemBounds(ImageViewer.ActiveItem, ImageViewerItemPart.Item);

            // IMPORTANT NOTE: The SelectAreaView we render the control points inside and the shaded area is added to the image viewer item itself
            // and not on the whole image viewer control so we need to map the touch points to item coordinates.
            var position = ImageViewer.ConvertPoint(null, ImageViewerCoordinateType.Control, ImageViewerCoordinateType.Item, e.Position);

            if (position.X < 0)
            {
                position.X = 0;
            }
            if (position.Y < 0)
            {
                position.Y = 0;
            }
            if (position.X > (int)itemBounds.Right)
            {
                position.X = (int)itemBounds.Right;
            }
            if (position.Y > (int)itemBounds.Bottom)
            {
                position.Y = (int)itemBounds.Bottom;
            }

            if (_dragThumbIndex != -1)
            {
                // Move this thumb

                // We have to find out which point we are and update the points from new corners accordingly
                switch (_dragThumbIndex)
                {
                case 0:
                    _controlPoints[0] = position;
                    break;

                case 1:
                    _controlPoints[0] = new LeadPoint(_controlPoints[0].X, position.Y);
                    break;

                case 2:
                    _controlPoints[0] = new LeadPoint(_controlPoints[0].X, position.Y);
                    _controlPoints[4] = new LeadPoint(position.X, _controlPoints[4].Y);
                    break;

                case 3:
                    _controlPoints[4] = new LeadPoint(position.X, _controlPoints[4].Y);
                    break;

                case 4:
                    _controlPoints[4] = position;
                    break;

                case 5:
                    _controlPoints[4] = new LeadPoint(_controlPoints[4].X, position.Y);
                    break;

                case 6:
                    _controlPoints[0] = new LeadPoint(position.X, _controlPoints[0].Y);
                    _controlPoints[4] = new LeadPoint(_controlPoints[4].X, position.Y);
                    break;

                case 7:
                    _controlPoints[0] = new LeadPoint(position.X, _controlPoints[0].Y);
                    break;

                default:
                    break;
                }

                _controlPoints          = PointsFromCorners(_controlPoints[0], _controlPoints[4]);
                controlPointsHasChanged = true;
            }
            else if (_isDraggingBody)
            {
                // Just update the points
                int dx = e.Change.X;
                int dy = e.Change.Y;
                if (dx != 0 || dy != 0)
                {
                    if (dx < 0 && _controlPoints[0].X + dx < 0)
                    {
                        dx = -_controlPoints[0].X;
                    }
                    if (dx > 0 && _controlPoints[4].X + dx > itemBounds.Right)
                    {
                        dx = (int)itemBounds.Right - _controlPoints[4].X;
                    }
                    if (dy < 0 && _controlPoints[0].Y + dy < 0)
                    {
                        dy = -_controlPoints[0].Y;
                    }
                    if (dy > 0 && _controlPoints[4].Y + dy > itemBounds.Bottom)
                    {
                        dy = (int)itemBounds.Bottom - _controlPoints[4].Y;
                    }

                    for (var i = 0; i < _controlPoints.Length; i++)
                    {
                        _controlPoints[i].X += dx;
                        _controlPoints[i].Y += dy;
                    }
                    controlPointsHasChanged = true;
                }
            }

            if (controlPointsHasChanged)
            {
                UpdateImagePoints();
                UpdateSelectedAreaView();
                imageViewer.Invalidate(LeadRectD.Empty);
            }

            e.IsHandled = true;
        }
コード例 #15
0
        private void InitializeViewer(ImageViewer viewer)
        {
            // Appearance
             viewer.BackColor = SystemColors.AppWorkspace;
             viewer.Dock = DockStyle.Fill;

             // Set Scale-to-Gray
             RasterPaintProperties properties = RasterPaintProperties.Default;
             properties.PaintDisplayMode = RasterPaintDisplayModeFlags.Bicubic | RasterPaintDisplayModeFlags.ScaleToGray;
             properties.PaintEngine = RasterPaintEngine.GdiPlus;
             properties.UsePaintPalette = true;
             viewer.PaintProperties = properties;
        }
コード例 #16
0
 /// <summary>
 /// Subscribes to image viewer events.
 /// </summary>
 /// <param name="imageViewer">The image viewer.</param>
 private void SubscribeToImageViewerEvents(ImageViewer imageViewer)
 {
     imageViewer.FocusedIndexChanged += new EventHandler <FocusedIndexChangedEventArgs>(ImageViewer_FocusedIndexChanged);
     imageViewer.VisualToolChanged   += new EventHandler <VisualToolChangedEventArgs>(ImageViewer_VisualToolChanged);
 }
コード例 #17
0
 void Button_TouchUpInside(object sender, EventArgs e)
 {
     PhotoIndex = Buttons.IndexOf((UIButton)sender);
     ImageViewer.OpenDNAPhotoViewer(ImageViews[(int)PhotoIndex].Image, ImageViews.Select(img => img.Image).ToList(), this, this);
 }
コード例 #18
0
 private void ZoomOutClick(object sender, RoutedEventArgs e)
 {
     ImageViewer.ZoomOutClick(sender, e);
 }
コード例 #19
0
 void IImageViewerHeaderDelegate.OnClose()
 {
     ImageViewer.CloseDNAPhotoViewer();
 }
コード例 #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DilateForm"/> class.
 /// </summary>
 /// <param name="viewer">The image viewer for image preview.</param>
 public DilateForm(ImageViewer viewer)
     : base(viewer, "Morphological.Dilate",
            new ImageProcessingParameter("Window Radius", 1, 16, 3))
 {
 }
コード例 #21
0
        protected override bool CalculatePoints(Image <Gray, ushort> origImage, Image <Gray, byte> maskImage, string name, string enumName)
        {
            using (VectorOfVectorOfPoint contour = new VectorOfVectorOfPoint())
            {
                try
                {
                    CvInvoke.FindContours(maskImage, contour, null, RetrType.List, ChainApproxMethod.ChainApproxNone);

                    int verticalCenterLine = maskImage.Width / 2;
                    int magicNumber1       = 2000;

                    for (int i = 0; i < contour.Size; i++)
                    {
                        Point[] _coordinateList = contour[i].ToArray();

                        if (_coordinateList.Length > 300)
                        {
                            maskImage.SetValue(255.0, maskImage);

                            if (_showImages)
                            {
                                using (var tempImage = new Image <Gray, byte>(maskImage.Size))
                                {
                                    maskImage.CopyTo(tempImage);
                                    tempImage.Draw(_coordinateList, new Gray(100.0), 2);
                                    ImageViewer.Show(tempImage, "BorderSearcher_Emgu2 - contour points");

                                    GeneralImageHandling.SaveImage(name, _ownFolderNameForSaving, "MaskImage" + enumName, tempImage, _logger);
                                }

                                using (var tempImage = new Image <Gray, ushort>(origImage.Size))
                                {
                                    origImage.CopyTo(tempImage);
                                    tempImage.Draw(_coordinateList, new Gray(200.0), 2);
                                    ImageViewer.Show(tempImage, "BorderSearcher_Emgu2 - contour points");

                                    GeneralImageHandling.SaveImage(name, _ownFolderNameForSaving, "OrigImage" + enumName, tempImage, _logger);
                                }
                            }

                            for (int j = 0; j < contour[i].Size - 1; j++)
                            {
                                if ((_coordinateList[j].Y != _coordinateList[j + 1].Y) && (Math.Abs(_coordinateList[j].Y - _coordinateList[j + 1].Y) < magicNumber1))
                                {
                                    if (_coordinateList[j].X + _borderSkipSize < verticalCenterLine)
                                    {
                                        if (_borderPoints[_coordinateList[j].Y, 0] < _coordinateList[j].X + _borderSkipSize)
                                        {
                                            _borderPoints[_coordinateList[j].Y, 0] = _coordinateList[j].X + _borderSkipSize;
                                        }
                                    }
                                    else if (_coordinateList[j].X - _borderSkipSize > verticalCenterLine)
                                    {
                                        if (_borderPoints[_coordinateList[j].Y, 1] > _coordinateList[j].X - _borderSkipSize)
                                        {
                                            _borderPoints[_coordinateList[j].Y, 1] = _coordinateList[j].X - _borderSkipSize;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    _logger?.ErrorLog($"Exception occured: {ex}.", ClassName);
                    return(false);
                }
            }
        }
コード例 #22
0
        private void barcodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (img == null) // Função para gerir métodos para processar barcodes
            {
                return;
            }


            Cursor = Cursors.WaitCursor; // clock cursor

            //Variavéis
            int[]  matrix       = new int[4]; //[xf,xi,yf,yi]
            Point  bc_centroid1 = new Point(0, 0);
            Size   bc_size1     = new Size(0, 0);
            string bc_image1    = "ola";
            string bc_number1   = "ola";
            Size   bc_size2     = new Size(0, 0);
            string bc_image2    = "ola";
            string bc_number2   = "ola";
            Point  bc_centroid2 = new Point(0, 0);

            float angleRad = 0;
            int   angle    = 1;

            switch (ImageType()) //Ver o tipo de imagem
            {
            case 1:
                Console.WriteLine("Função do tipo 1");
                ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);
                break;

            case 2:
                Console.WriteLine("Função do tipo 2");
                ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);
                break;

            case 3:
                Console.WriteLine("Função do tipo 3");
                ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);
                break;



            case 4:
                Console.WriteLine("Função do tipo 4");
                ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);
                break;

            case 5:
                Console.WriteLine("Função do tipo 5");
                ImageClass.BarCodeReader(img, ImageType(), out bc_centroid1, out bc_size1, out bc_image1, out bc_number1, out bc_centroid2, out bc_size2, out bc_image2, out bc_number2);
                break;

            default:
                Console.WriteLine("Default case");
                break;
            }

            ImageViewer.Image = img.Bitmap;
            ImageViewer.Refresh();    // refresh image on the screen

            Cursor = Cursors.Default; // normal cursor
        }
コード例 #23
0
ファイル: SURFFeature.cs プロジェクト: zliu100/emgu_openCV
        static void Run()
        {
            SURFDetector surfParam = new SURFDetector(500, false);

            Image <Gray, Byte> modelImage = new Image <Gray, byte>("box.png");

            //extract features from the object image
            ImageFeature[] modelFeatures = surfParam.DetectFeatures(modelImage, null);

            //Create a Feature Tracker
            Features2DTracker tracker = new Features2DTracker(modelFeatures);

            Image <Gray, Byte> observedImage = new Image <Gray, byte>("box_in_scene.png");

            Stopwatch watch = Stopwatch.StartNew();

            // extract features from the observed image
            ImageFeature[] imageFeatures = surfParam.DetectFeatures(observedImage, null);

            Features2DTracker.MatchedImageFeature[] matchedFeatures = tracker.MatchFeature(imageFeatures, 2, 20);
            matchedFeatures = Features2DTracker.VoteForUniqueness(matchedFeatures, 0.8);
            matchedFeatures = Features2DTracker.VoteForSizeAndOrientation(matchedFeatures, 1.5, 20);
            HomographyMatrix homography = Features2DTracker.GetHomographyMatrixFromMatchedFeatures(matchedFeatures);

            watch.Stop();

            //Merge the object image and the observed image into one image for display
            Image <Gray, Byte> res = modelImage.ConcateVertical(observedImage);

            #region draw lines between the matched features
            foreach (Features2DTracker.MatchedImageFeature matchedFeature in matchedFeatures)
            {
                PointF p = matchedFeature.ObservedFeature.KeyPoint.Point;
                p.Y += modelImage.Height;
                res.Draw(new LineSegment2DF(matchedFeature.SimilarFeatures[0].Feature.KeyPoint.Point, p), new Gray(0), 1);
            }
            #endregion

            #region draw the project region on the image
            if (homography != null)
            { //draw a rectangle along the projected model
                Rectangle rect = modelImage.ROI;
                PointF[]  pts  = new PointF[] {
                    new PointF(rect.Left, rect.Bottom),
                    new PointF(rect.Right, rect.Bottom),
                    new PointF(rect.Right, rect.Top),
                    new PointF(rect.Left, rect.Top)
                };
                homography.ProjectPoints(pts);

                for (int i = 0; i < pts.Length; i++)
                {
                    pts[i].Y += modelImage.Height;
                }

                res.DrawPolyline(Array.ConvertAll <PointF, Point>(pts, Point.Round), true, new Gray(255.0), 5);
            }
            #endregion

            ImageViewer.Show(res, String.Format("Matched in {0} milliseconds", watch.ElapsedMilliseconds));
        }
コード例 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlurForm"/> class.
 /// </summary>
 /// <param name="viewer">The image viewer for image preview.</param>
 public BlurForm(ImageViewer viewer)
     : base(viewer, "Convolution.Blur",
            new ImageProcessingParameter("Window Radius", 1, 16, 3))
 {
 }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PixelateForm"/> class.
 /// </summary>
 /// <param name="viewer">The image viewer for image preview.</param>
 public PixelateForm(ImageViewer viewer)
     : base(viewer,
            "Pixelate",
            new ImageProcessingParameter("Cell size (pixels)", 2, 100, 4))
 {
 }
コード例 #26
0
        private void OpenFile(string fileName)
        {
            picsize     = width * height;
            datasize    = (picsize >> 1) * 3;
            yuvframeL   = new byte[(picsize >> 1) * 3];
            yuvframeR   = new byte[(picsize >> 1) * 3];
            bgrimage    = new Image <Bgr, byte>(width * 2, height);
            mergedframe = new byte[bgrimage.Width * bgrimage.Height * 3];
            if (!File.Exists(fileName))
            {
                MessageBox.Show("file does not exist");
                return;
            }
            if (File.OpenRead(fileName).CanRead)
            {
                yuvFile[m_tot_view] = File.OpenRead(fileName);
                m_tot_view++;
            }

            int Count = 0;//指示数字位数

            if (Char.IsNumber(fileName, fileName.Length - 5))
            {
                Count++;
                if (Char.IsNumber(fileName, fileName.Length - 6))
                {
                    Count++;
                    if (Char.IsNumber(fileName, fileName.Length - 7))
                    {
                        Count++;
                    }
                }
            }
            else
            {
                MessageBox.Show("错误的文件名格式,最后一位需为数字!", "error");
                Environment.Exit(0);
            }
            // MessageBox.Show(Count.ToString(), "Count");
            //分配文件流
            for (int i = Int32.Parse(fileName.Substring(fileName.Length - 4 - Count, Count)) + 1; ; i++)
            {
                var filestr = i.ToString();
                if (i < 10)
                {
                    fileName = fileName.Remove(fileName.Length - 5, 1);
                }
                else if (i < 100)
                {
                    fileName = fileName.Remove(fileName.Length - 6, 2);
                }
                else
                {
                    fileName = fileName.Remove(fileName.Length - 7, 3);
                }
                fileName = fileName.Insert(fileName.Length - 4, filestr);
                if (File.Exists(fileName) && File.OpenRead(fileName).CanRead)
                {
                    yuvFile[m_tot_view] = File.OpenRead(fileName);
                    m_tot_view++;
                }
                else
                {
                    break;
                }
            }

            if (m_tot_view < 2)
            {
                MessageBox.Show("至少要有2个视点", "error");
                Environment.Exit(0);
            }
            m_tot_frame = (int)(yuvFile[0].Length / yuvframeL.Length);
            imageviewer = new ImageViewer();
            imageviewer.Select();                            //激活窗口

            imageviewer.KeyDown      += imageviewer_KeyDown; //定义快捷键操作
            imageviewer.WindowState   = System.Windows.Forms.FormWindowState.Normal;
            imageviewer.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

            imageviewer.ImageBox.FunctionalMode = ImageBox.FunctionalModeOption.Minimum;
            ImageFullScreen(ref imageviewer);
            PlayOneFrame(current_view, ref current_frame);
        }
コード例 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PosterizeForm"/> class.
 /// </summary>
 /// <param name="viewer">The image viewer for image preview.</param>
 public PosterizeForm(ImageViewer viewer)
     : base(viewer,
            "Posterize",
            new ImageProcessingParameter("Levels", 2, 256, 6))
 {
 }
コード例 #28
0
 private void imageViewer_Click(object sender, EventArgs e)
 {
     ImageViewer imageViewer = (ImageViewer)sender;
 }
コード例 #29
0
        public static bool ProcessShapeMatching(ref Image <Gray, Byte> templateImage, out Image <Gray, Byte> targetImage)
        {
            positions = new List <Polygon>();
            Contour <Point> templateContours = GetEdgeContours(templateImage, null, 100);
            Contour <Point> targetContours   = GetEdgeContours(targetImage, maskImage, 100);

            MCvBox2D box = templateContours.GetMinAreaRect();

            double precision         = 0.0001;
            double distanceThreshold = 0.4;
            int    nCCompLevels      = 2;                 // connected components have 2 levels. 1 of the outer boundary en possibly 1 for the inner boundaries (holes)

            using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
            {
                //Find largest connected component countour in the template
                Contour <Point> templateContour = new Contour <Point>(storage);
                double          largestArea     = 0;
                for (Contour <Point> cont = templateContours; cont != null; cont = cont.HNext)
                {
                    if (cont.Area > largestArea)
                    {
                        templateContour = cont;
                    }
                }
                if (templateContour == null)
                {
                    throw new NullReferenceException("No contours found in the template image");
                }

                // reduce the nr of vertices in the template polygons
                templateContour = templateContour.ApproxPoly(templateContour.Perimeter * precision, nCCompLevels, storage);

                // reduce the nr of  vertices in the target polygons
                if (templateContour.Area > targetImage.Height * targetImage.Width / 1000) //only consider contours plausible area
                {
                    double distance = 0;
                    for (Contour <Point> targetContour = targetContours; targetContour != null; targetContour = targetContour.HNext)
                    {
                        if (targetContour.Area < targetImage.Height * targetImage.Width / 1000) //only consider contours plausible area
                        {
                            continue;
                        }

                        Contour <Point> approximatedTargetContour = targetContour.ApproxPoly(targetContour.Perimeter * precision, nCCompLevels, storage);
                        distance += templateContour.MatchShapes(approximatedTargetContour, CONTOURS_MATCH_TYPE.CV_CONTOURS_MATCH_I3);

                        ImageViewer.Show(DrawContours(targetImage, approximatedTargetContour, new Bgr(Color.Cyan), 2, 0), "contour");

                        //This is the smelly part, it only works when the number of holes in the template is zero or one
                        // in the template and target shapes are the
                        if ((templateContour.VNext != null) && (targetContour.VNext != null))
                        {
                            distance += templateContour.MatchShapes(approximatedTargetContour, CONTOURS_MATCH_TYPE.CV_CONTOURS_MATCH_I3);
                        }
                        if ((templateContour.VNext != null) && (targetContour.VNext == null))
                        {
                            continue; // no match
                        }
                        if ((templateContour.VNext == null) && (targetContour.VNext != null))
                        {
                            continue; // no match
                        }
                        //http://stackoverflow.com/questions/15555615/equivalent-of-hierarchy-in-emgu

                        if (distance > distanceThreshold)
                        {
                            continue;
                        }

                        // we have a match, let's add the position
                        positions.Add(MCvBox2D2Polygon(targetContour.GetMinAreaRect()));

                        // draw some annotation
                        Image <Bgr, Byte> imageAnotated = DrawContours(targetImage, approximatedTargetContour, new Bgr(Color.Salmon), 2, nCCompLevels);
                        MCvBox2D          boxi          = approximatedTargetContour.GetMinAreaRect();
                        imageAnotated.Draw(boxi, new Bgr(Color.Turquoise), 2);
                        ImageViewer.Show(imageAnotated, String.Format("current contour {0}", distance));
                    }
                }
            }
            return(false);
        }
コード例 #30
0
        void ReleaseDesignerOutlets()
        {
            if (FeatureMap != null)
            {
                FeatureMap.Dispose();
                FeatureMap = null;
            }

            if (GetImage != null)
            {
                GetImage.Dispose();
                GetImage = null;
            }

            if (imageLabel != null)
            {
                imageLabel.Dispose();
                imageLabel = null;
            }

            if (ImageViewer != null)
            {
                ImageViewer.Dispose();
                ImageViewer = null;
            }

            if (messageLabel != null)
            {
                messageLabel.Dispose();
                messageLabel = null;
            }

            if (ProcessImage != null)
            {
                ProcessImage.Dispose();
                ProcessImage = null;
            }

            if (ResetImage != null)
            {
                ResetImage.Dispose();
                ResetImage = null;
            }

            if (Root != null)
            {
                Root.Dispose();
                Root = null;
            }

            if (switchSwitch != null)
            {
                switchSwitch.Dispose();
                switchSwitch = null;
            }

            if (textAperture != null)
            {
                textAperture.Dispose();
                textAperture = null;
            }

            if (textThreshold1 != null)
            {
                textThreshold1.Dispose();
                textThreshold1 = null;
            }

            if (textThreshold2 != null)
            {
                textThreshold2.Dispose();
                textThreshold2 = null;
            }
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: anlEl/EMGUCV
        private static void withKeyframes(bool isFast, string videoSource = null)
        {
            ImageViewer viewer = new ImageViewer();

            try
            {
                Capture           capture  = videoSource != null ? new Capture(videoSource) : new Capture(0);
                Image <Bgr, Byte> result   = null;
                KeyFrame          keyFrame = null;

                Application.Idle += new EventHandler(delegate(object sender, EventArgs e)
                {
                    counter++;
                    if (keyFrames.Count < 15)
                    {
                        IDrawer drawer;
                        if (isFast)
                        {
                            drawer = new FastDrawer();
                        }
                        else
                        {
                            drawer = new SURFDrawer();
                        }
                        try
                        {
                            Mat frame = capture.QueryFrame();
                            if (frame.Width > 720 || frame.Height > 480)
                            {
                                double width  = 720.0 / frame.Width;
                                double height = 480.0 / frame.Height;

                                CvInvoke.Resize(frame, frame, new Size(), width, height, Inter.Linear);
                            }
                            Image <Bgr, Byte> framebuffer = frame.ToImage <Bgr, Byte>();
                            if (keyFrames.Count == 0)
                            {
                                keyFrames.Add(new KeyFrame()
                                {
                                    Frame = framebuffer
                                });
                            }
                            for (int i = keyFrames.Count - 1; i >= 0; i--)
                            {
                                KeyFrame kf = keyFrames[i];
                                drawer.FindMatch(kf, framebuffer, keyFrames);
                                if (counter == 65)
                                {
                                    //homography ile camera pozu ayarla, nesneyi koy
                                }
                                if (drawer.homography != null)
                                {
                                    KeyFrame buffer_kf = keyFrames[keyFrames.Count - 1];
                                    if (kf != buffer_kf)
                                    {
                                        keyFrames[i] = buffer_kf;
                                        keyFrames[keyFrames.Count - 1] = kf;
                                    }
                                    keyFrame = kf;
                                    break;
                                }
                                if (i == 0)
                                {
                                    if (drawer.homography == null)
                                    {
                                        keyFrames.Add(new KeyFrame()
                                        {
                                            Frame = framebuffer, KeyPoints = drawer.observedKeyPoints, Descriptors = drawer.observedDescriptors
                                        });
                                    }
                                }
                                drawer.Clear();
                            }
                            result = frame.ToImage <Bgr, Byte>();
                            if (keyFrame != null)
                            {
                                result = drawer.Draw(keyFrame, framebuffer);
                            }

                            viewer.Width = frame.Width * 2 + 50;
                            viewer.Image = result;
                            //result.Dispose();
                        }
                        catch (Exception ex1)
                        {
                        }
                        finally
                        {
                            result.Dispose();
                            drawer.Dispose();
                        }
                    }
                    else
                    {
                        keyFrames.RemoveRange(0, keyFrames.Count / 2);
                    }
                });
            }
            catch
            {
            }
            viewer.ShowDialog();
        }
コード例 #32
0
        /// <summary>
        /// Initialize the application
        /// </summary>
        private void InitClass( )
        {
            // setup our caption
            Messager.Caption = "LEADTOOLS for .NET C# Twain Multipage Demo";
            Text             = Messager.Caption;

            // initialize the _viewer object
            _viewer           = new ImageViewer();
            _viewer.Dock      = DockStyle.Fill;
            _viewer.BackColor = Color.DarkGray;
            Controls.Add(_viewer);
            _viewer.BringToFront();

            // initialize the codecs object
            _codecs = new RasterCodecs();

            if (TwainSession.IsAvailable(this.Handle))
            {
                try
                {
                    // setup the Twain session object
                    _twainSession = new TwainSession();

                    //For 32-bit driver support in 64-bit applications, use the following TWAIN initialization method instead:
                    //_twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Twain .NET", "Version 14", "LEADTools Twain test sample", TwainStartupFlags.UseThunkServer);

                    // start up the Twain session
                    _twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Twain .NET", "Version 14", "LEADTools Twain test sample", TwainStartupFlags.None);
                }
                catch (TwainException ex)
                {
                    if (ex.Code == TwainExceptionCode.InvalidDll)
                    {
                        _miFileAcquire.Enabled        = false;
                        _miFileAcquireCleanup.Enabled = false;
                        _miFileSelectSource.Enabled   = false;
                        Messager.ShowError(this, "You have an old version of TWAINDSM.DLL. Please download latest version of this DLL from www.twain.org");
                    }
                    else
                    {
                        _miFileAcquire.Enabled        = false;
                        _miFileAcquireCleanup.Enabled = false;
                        _miFileSelectSource.Enabled   = false;
                        Messager.ShowError(this, ex);
                    }
                }
                catch (Exception ex)
                {
                    Messager.ShowError(this, ex);
                    _miFileAcquire.Enabled        = false;
                    _miFileAcquireCleanup.Enabled = false;
                    _miFileSelectSource.Enabled   = false;
                }
            }
            else
            {
                _miFileAcquire.Enabled        = false;
                _miFileAcquireCleanup.Enabled = false;
                _miFileSelectSource.Enabled   = false;
            }

            // setup the other variables
            _fileName   = string.Empty;
            _fileFormat = RasterImageFormat.Tif;
            _pageNo     = 0;

            UpdateMyControls();
            UpdateStatusBarText();
        }
コード例 #33
0
 private void OpenCommandExecuted(object sender, ExecutedRoutedEventArgs e)
 {
     ImageViewer.OpenExecuted(sender, e);
 }
コード例 #34
0
 /// <summary>
 /// Unsubscribes from image viewer events.
 /// </summary>
 /// <param name="imageViewer">The image viewer.</param>
 private void UnsubscribeFromImageViewerEvents(ImageViewer imageViewer)
 {
     imageViewer.FocusedIndexChanged -= ImageViewer_FocusedIndexChanged;
     imageViewer.VisualToolChanged   -= ImageViewer_VisualToolChanged;
 }
コード例 #35
0
ファイル: Image.cs プロジェクト: plamkata/TestProjects
 public void view(ImageViewer viewer, bool isThumbnail)
 {
     if (isThumbnail)
     {
         viewer.viewThumbnail(this);
     }
     else
     {
         viewer.viewImage(this);
     }
 }