コード例 #1
0
        // Update methods
        private async void UpdateScannerInfo()
        {
            while (SelectedScanner == null)
            {
                try
                {
                    SelectedScanner = await ImageScanner.FromIdAsync(_selectedDevice.Id);

                    ScannerSources      = ScannerHelper.GetSupportedScanSources(SelectedScanner);
                    UIIsScannerSelected = true;
                }
                catch (Exception ex)
                {
                    // https://stackoverflow.com/questions/15772373/error-code-when-trying-to-connect-to-a-scanner-using-wpf

                    Debug.WriteLine("MainViewModel - Scanner is busy");
                    Debug.WriteLine(ex);
                }
            }

            // Set the default properties
            var defaultScannerSource = SelectedScanner.DefaultScanSource;

            if (ScannerSources.Contains(defaultScannerSource))
            {
                SelectedScannerSource = defaultScannerSource;
            }
        }
コード例 #2
0
        public async Task <ScanSourceDetails> GetSupportedScanSources
            (String deviceId)
        {
            // Check whether each of the known scan sources is available
            // for the scanner with the provided ID
            var scanSources = new[]
            {
                ImageScannerScanSource.Flatbed,
                ImageScannerScanSource.Feeder,
                ImageScannerScanSource.AutoConfigured
            };

            var scanner = await ImageScanner.FromIdAsync(deviceId);

            var supportedSources = scanSources
                                   .Where(x => scanner.IsScanSourceSupported(x))
                                   .Select(x => new ScanSourceDetailsItem
            {
                SourceType      = x,
                SupportsPreview = scanner.IsPreviewSupported(x)
            })
                                   .ToList();

            var results = new ScanSourceDetails
            {
                SupportedScanSources = supportedSources,
                DefaultScanSource    = scanner.DefaultScanSource
            };

            return(results);
        }
コード例 #3
0
 /// <summary>
 /// Process video, the worker thread
 /// </summary>
 private void ProcessVideo()
 {
     using (Video video = new Video()){
         try{
             video.Open(this.currentDevice);
             video.Enabled = true;
             using (ImageScanner scanner = new ImageScanner()){
                 scanner.Cache = true;
                 this.CaptureVideo(video, scanner);
             }
             video.Enabled = false;
         }
         catch (ZBarException ex) {
             lock (this.drawLock){
                 this.toDraw  = null;
                 this.symbols = null;
             }
             GLib.IdleHandler hdl = delegate(){
                 if (this.Stopped != null)
                 {
                     this.Stopped(this, new EventArgs());
                 }
                 if (this.Error != null)
                 {
                     this.Error(this, new ErrorEventArgs(ex.Message, ex));
                 }
                 this.QueueDraw();
                 return(false);
             };
             GLib.Idle.Add(hdl);
         }
     }
 }
コード例 #4
0
        public async Task <IEnumerable <ScannerModel> > GetScannersAsync()
        {
            // String to be used to enumerate scanners
            var deviceSelector = ImageScanner.GetDeviceSelector();

            var scanners = await DeviceInformation.FindAllAsync(deviceSelector);

            var result = scanners
                         .Select(x => new ScannerModel
            {
                Id        = x.Id,
                Name      = x.Name,
                IsDefault = x.IsDefault,
                IsEnabled = x.IsEnabled,
            });

            return(result);

            // Alternatively, a watcher can be used, which raises events as items are located/added/removed/updated:
            //var watcher = DeviceInformation.CreateWatcher(deviceSelector);
            //watcher.EnumerationCompleted += (sender, args) => Debug.WriteLine("Scanners enumerated");
            //watcher.Added += (sender, args) => Debug.WriteLine("Scanner added - {0}", args.Name);
            //watcher.Removed += (sender, args) => Debug.WriteLine("Scanner removed - {0}", args.Id);
            //watcher.Updated += (sender, args) => Debug.WriteLine("Scanner updated - {0}", args.Id);
            //watcher.Start();
        }
コード例 #5
0
        public async Task <IEnumerable <StorageFile> > ScanPicturesAsync(
            String scannerDeviceId, ImageScannerScanSource source,
            StorageFolder destinationFolder,
            Double hScanPercent, Double vScanPercent)
        {
            var scanner = await ImageScanner.FromIdAsync(scannerDeviceId);

            if (scanner.IsScanSourceSupported(source))
            {
                ConfigureScanner(scanner, source, hScanPercent, vScanPercent);

                var scanResult = await scanner
                                 .ScanFilesToFolderAsync(source, destinationFolder);

                var results = new List <StorageFile>();
                // Caution - enumerating this list (foreach) will result in a
                // COM exception.  Instead, just walk the collection by index
                // and build a new list.
                for (var i = 0; i < scanResult.ScannedFiles.Count; i++)
                {
                    results.Add(scanResult.ScannedFiles[i]);
                }
                return(results);
            }
            return(null);
        }
コード例 #6
0
        public void Scan(Image source)
        {
            OCR = string.Empty;

            var capture = CaptureImage(source);

            if (Image == null)
            {
                Image = capture;
                EventStream.Publish(new FileModified(Id + ".png", Image.ToBytes(ImageFormat.Png)));
            }

            var matcher = new AccordImageMatcher(Image);
            var results = matcher.Compare(capture, 0.9f);

            Exists = results.Any(each => each.Similarity >= 0.95f && Rectangle.Equals(each.Rectangle));

            /*if (Exists) {
             *  Rectangle.SetBorderColor(1, 0, 1, 0);
             * }
             * else {
             *  Rectangle.SetBorderColor(1, 1, 0, 0);
             * }*/

            if (Rectangle.Width > 0 && Rectangle.Height > 0)
            {
                OCR = ImageScanner.ReadText(new Bitmap(Image)).Replace("\n", "");
            }

            UpdateLabel();
        }
コード例 #7
0
        //识别二维码
        public bool DoCheckTicket(ref string strQrCode)
        {
            DataTickCam data = new DataTickCam();

            if (!mainWin.CapTicket(data))
            {
                return(false);
            }

            strQrCode = string.Empty;
            using (Bitmap bmGray = WinCall.BitmapConvetGray(data.bm))
            {
                //垂直翻转
                bmGray.RotateFlip(RotateFlipType.Rotate90FlipX);
                using (ImageScanner scanner = new ImageScanner())
                {
                    scanner.SetConfiguration(SymbolType.None, Config.Enable, 1);
                    List <Symbol> symbols = scanner.Scan(bmGray);
                    WinCall.TraceMessage(string.Format("***Ticket syms={0}", symbols.Count)); //! for test

                    foreach (var sym in symbols)
                    {
                        var symType = sym.GetType();
                        if (!string.IsNullOrEmpty(sym.Data))
                        {
                            strQrCode = sym.Data;
                            break; //只取一个结果
                        }
                    }
                }
            }
            data.bm.Dispose();
            return(false == string.IsNullOrEmpty(strQrCode));
        }
コード例 #8
0
        private async void cmbxScanner_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedDevice  = (DeviceInformation)cmbxScanner.SelectedItem;
            selectedScanner = await ImageScanner.FromIdAsync(selectedDevice.Id);

            scannerSources = ScannerHelper.GetSupportedScanSources(selectedScanner);
            cmbxScannerSource.ItemsSource = scannerSources;
        }
コード例 #9
0
        /// <summary>
        /// Scans the images from the scanner with auto configured settings
        /// The scanning is allowed only if the selected scanner supports Device Auto-Configured Scanning.
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the use has already cancelled the scenario
                if (ModelDataContext.ScenarioRunning)
                {
                    if (myScanner.IsScanSourceSupported(ImageScannerScanSource.AutoConfigured))
                    {
                        cancellationToken = new CancellationTokenSource();

                        // Set the scan file format to PNG, if available
                        if (myScanner.AutoConfiguration.IsFormatSupported(ImageScannerFormat.Png))
                        {
                            myScanner.AutoConfiguration.Format = ImageScannerFormat.Png;
                        }

                        rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);
                        var progress = new Progress <UInt32>(ScanProgress);
                        // Scan API call to start scanning with Auto-Configured settings
                        var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.AutoConfigured, folder).AsTask(cancellationToken.Token, progress);

                        ModelDataContext.ScenarioRunning = false;
                        if (result.ScannedFiles.Count > 0)
                        {
                            Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
                            if (result.ScannedFiles.Count > 1)
                            {
                                Utils.UpdateFileListData(result.ScannedFiles, ModelDataContext);
                            }
                        }
                        else
                        {
                            rootPage.NotifyUser("There were no files scanned.", NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        ModelDataContext.ScenarioRunning = false;
                        rootPage.NotifyUser("The selected scanner does not support Device Auto-Configured Scanning.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, ModelDataContext);
            }
        }
コード例 #10
0
        public void ConvertAndScanBMP()
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile("images/barcode.bmp");

            ImageScanner  scanner = new ImageScanner();
            List <Symbol> symbols = scanner.Scan(img);

            Assert.AreEqual(1, symbols.Count, "Didn't find the symbols");
            Assert.IsTrue(SymbolType.EAN13 == symbols[0].Type, "Didn't get the barcode type right");
            Assert.AreEqual("0123456789012", symbols[0].Data, "Didn't read the correct barcode");
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: Tobbe1974/PoE-Buff-Watcher
        private static (Image, Image) ReadImage(Image image)
        {
            var time = Stopwatch.StartNew();

            using var imageScanner = new ImageScanner(image);
            var buffs   = imageScanner.FindBuffs();
            var debuffs = imageScanner.FindDebuffs();

            time.Stop();

            return(buffs, debuffs);
        }
コード例 #12
0
        /// <summary>
        /// Gets all available Image Formats for a Scan Source
        /// </summary>
        /// <param name="scanner"></param>
        /// <param name="source"></param>
        /// <returns>List with all available ImageScannerFormats for the given source</returns>
        public static List <ImageScannerFormat> GetSupportedImageFormats(ImageScanner scanner, ImageScannerScanSource source)
        {
            List <ImageScannerFormat> availableFormats = new List <ImageScannerFormat>();

            switch (source)
            {
            case ImageScannerScanSource.Flatbed:     // Flatbed
            {
                foreach (ImageScannerFormat format in (ImageScannerFormat[])Enum.GetValues(typeof(ImageScannerFormat)))
                {
                    if (scanner.FlatbedConfiguration.IsFormatSupported(format))
                    {
                        availableFormats.Add(format);
                    }
                }
                break;
            }

            case ImageScannerScanSource.Feeder:     // Feeder
            {
                foreach (ImageScannerFormat format in (ImageScannerFormat[])Enum.GetValues(typeof(ImageScannerFormat)))
                {
                    if (scanner.FeederConfiguration.IsFormatSupported(format))
                    {
                        availableFormats.Add(format);
                    }
                }
                break;
            }

            case ImageScannerScanSource.AutoConfigured:     // Auto Configured
            {
                foreach (ImageScannerFormat format in (ImageScannerFormat[])Enum.GetValues(typeof(ImageScannerFormat)))
                {
                    if (scanner.AutoConfiguration.IsFormatSupported(format))
                    {
                        availableFormats.Add(format);
                    }
                }
                break;
            }

            case ImageScannerScanSource.Default:        // Catch the otherwise empty set by only providing Bitmap as option, as this is device independant
            {
                availableFormats.Add(ImageScannerFormat.DeviceIndependentBitmap);
                break;
            }
            }

            return(availableFormats);
        }
        /// <summary>
        /// Scans image from the Flatbed source of the scanner
        /// The scanning is allowed only if the selected scanner is equipped with a Flatbed
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the user has already canceled the scenario
                if (ModelDataContext.ScenarioRunning)
                {
                    if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Flatbed))
                    {
                        // Set the scan file format to Device Independent Bitmap (DIB)
                        myScanner.FlatbedConfiguration.Format = ImageScannerFormat.DeviceIndependentBitmap;

                        cancellationToken = new CancellationTokenSource();

                        rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);
                        // Scan API call to start scanning from the Flatbed source of the scanner.
                        var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Flatbed, folder).AsTask(cancellationToken.Token);

                        ModelDataContext.ScenarioRunning = false;
                        if (result.ScannedFiles.Count > 0)
                        {
                            Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
                        }
                        else
                        {
                            rootPage.NotifyUser("There are no files scanned from the Flatbed.", NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        ModelDataContext.ScenarioRunning = false;
                        rootPage.NotifyUser("The selected scanner does not report to be equipped with a Flatbed.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, ModelDataContext);
            }
        }
コード例 #14
0
        /// <summary>
        /// Gets all available Scan Sources for a scanner
        /// </summary>
        /// <param name="scanner"></param>
        /// <returns>List with all available ImageScannerScanSources for the given scanner</returns>
        public static List <ImageScannerScanSource> GetSupportedScanSources(ImageScanner scanner)
        {
            List <ImageScannerScanSource> availableScanSources = new List <ImageScannerScanSource>();

            foreach (ImageScannerScanSource scanSource in (ImageScannerScanSource[])Enum.GetValues(typeof(ImageScannerScanSource)))
            {
                if (scanner.IsScanSourceSupported(scanSource))
                {
                    if (scanSource != ImageScannerScanSource.Default)   // Disabling Default as it'll only be used for getting preferences from
                    {
                        availableScanSources.Add(scanSource);
                    }
                }
            }

            return(availableScanSources);
        }
コード例 #15
0
        /// <summary>
        /// Gets all available Colour Modes for a Scan Source
        /// </summary>
        /// <param name="scanner"></param>
        /// <param name="source"></param>
        /// <returns>List with all available ImageScannerColorMode for the given source</returns>
        public static List <ImageScannerColorMode> GetSupportedColourModes(ImageScanner scanner, ImageScannerScanSource source)
        {
            List <ImageScannerColorMode> availableColorModes = new List <ImageScannerColorMode>();

            switch (source)
            {
            case ImageScannerScanSource.Flatbed:     // Flatbed
            {
                foreach (ImageScannerColorMode colourMode in (ImageScannerColorMode[])Enum.GetValues(typeof(ImageScannerColorMode)))
                {
                    if (scanner.FlatbedConfiguration.IsColorModeSupported(colourMode))
                    {
                        availableColorModes.Add(colourMode);
                    }
                }
                break;
            }

            case ImageScannerScanSource.Feeder:     // Feeder
            {
                foreach (ImageScannerColorMode colourMode in (ImageScannerColorMode[])Enum.GetValues(typeof(ImageScannerColorMode)))
                {
                    if (scanner.FeederConfiguration.IsColorModeSupported(colourMode))
                    {
                        availableColorModes.Add(colourMode);
                    }
                }
                break;
            }

            case ImageScannerScanSource.AutoConfigured:     // Auto Configured
            {
                // Not possible, return empty List
                break;
            }

            case ImageScannerScanSource.Default:        // Catch the otherwise empty set by only providing Bitmap as option, as this is device independant
            {
                // Not possible, return empty List
                break;
            }
            }

            return(availableColorModes);
        }
コード例 #16
0
        /// <summary>
        /// Scans all the images from Feeder source of the scanner
        /// The scanning is allowed only if the selected scanner is equipped with a Feeder
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the use has already cancelled the scenario
                if (model.ScenarioRunning)
                {
                    if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Feeder))
                    {
                        // Set MaxNumberOfPages to zero to scanning all the pages that are present in the feeder
                        myScanner.FeederConfiguration.MaxNumberOfPages = 0;
                        myScanner.FeederConfiguration.Duplex           = tggDuplex.IsOn;
                        myScanner.FeederConfiguration.PageSize         = (Windows.Graphics.Printing.PrintMediaSize)model.ScannerDataContext.CurrentSize;

                        cancellationToken = new CancellationTokenSource();
                        rootPage.NotifyUser("Escaneando", NotifyType.StatusMessage);

                        // Scan API call to start scanning from the Feeder source of the scanner.
                        var operation = myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Feeder, folder);
                        operation.Progress = new AsyncOperationProgressHandler <ImageScannerScanResult, uint>(ScanProgress);
                        var result = await operation.AsTask <ImageScannerScanResult, UInt32>(cancellationToken.Token);

                        // Number of scanned files should be zero here since we already processed during scan progress notifications all the files that have been scanned
                        rootPage.NotifyUser("Escaneo completado.", NotifyType.StatusMessage);
                        model.ScenarioRunning = false;
                    }
                    else
                    {
                        model.ScenarioRunning = false;
                        rootPage.NotifyUser("El escáner seleccionado indica no tener Feeder.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, model);
            }
        }
        /// <summary>
        /// Scans all the images from Feeder source of the scanner
        /// The scanning is allowed only if the selected scanner is equipped with a Feeder
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the use has already cancelled the scenario
                if (ModelDataContext.ScenarioRunning)
                {
                    if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Feeder))
                    {
                        // Set MaxNumberOfPages to zero to scanning all the pages that are present in the feeder
                        myScanner.FeederConfiguration.MaxNumberOfPages = 0;
                        cancellationToken = new CancellationTokenSource();
                        rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);

                        // Scan API call to start scanning from the Feeder source of the scanner.
                        var operation = myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Feeder, folder);
                        operation.Progress = new AsyncOperationProgressHandler <ImageScannerScanResult, uint>(ScanProgress);
                        var result = await operation.AsTask <ImageScannerScanResult, UInt32>(cancellationToken.Token);

                        // Number of scanned files should be zero here since we already processed during scan progress notifications all the files that have been scanned
                        rootPage.NotifyUser("Scanning is complete.", NotifyType.StatusMessage);
                        ModelDataContext.ScenarioRunning = false;
                    }
                    else
                    {
                        ModelDataContext.ScenarioRunning = false;
                        rootPage.NotifyUser("The selected scanner does not report to be equipped with a Feeder.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, ModelDataContext);
            }
        }
コード例 #18
0
        public async Task <BitmapImage> ScanPicturePreviewAsync
            (String scannerDeviceId, ImageScannerScanSource scanSource)
        {
            var scanner = await ImageScanner.FromIdAsync(scannerDeviceId);

            if (scanner.IsPreviewSupported(scanSource))
            {
                var stream = new InMemoryRandomAccessStream();
                var result =
                    await scanner.ScanPreviewToStreamAsync(scanSource, stream);

                if (result.Succeeded)
                {
                    var thumbnail = new BitmapImage();
                    thumbnail.SetSource(stream);
                    return(thumbnail);
                }
            }
            return(null);
        }
コード例 #19
0
        /// <summary>
        /// Scans the images from the scanner with default settings
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the use has already cancelled the scenario
                if (ModelDataContext.ScenarioRunning)
                {
                    cancellationToken = new CancellationTokenSource();

                    rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);
                    var progress = new Progress <UInt32>(ScanProgress);
                    // Scan API call to start scanning
                    var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Default, folder).AsTask(cancellationToken.Token, progress);

                    ModelDataContext.ScenarioRunning = false;
                    if (result.ScannedFiles.Count > 0)
                    {
                        Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
                        if (result.ScannedFiles.Count > 1)
                        {
                            Utils.UpdateFileListData(result.ScannedFiles, ModelDataContext);
                        }
                    }
                    else
                    {
                        rootPage.NotifyUser("There were no files scanned.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, ModelDataContext);
            }
        }
コード例 #20
0
        public static string GetBarcode_ZBAR(string fileName)
        {
            string text;

            using (var img = new Bitmap(fileName))
            {
                text = "";
                if (img.Width > 0 && img.Height > 0)
                {
                    System.Drawing.Image oBitmap       = System.Drawing.Image.FromFile(fileName);
                    ImageScanner         oImageScanner = new ImageScanner();
                    var symbols = oImageScanner.Scan(oBitmap);
                    if (symbols.Count > 0)
                    {
                        text = symbols[0].ToString();
                        text = text.Substring(8);
                    }
                }
            }
            return(text);
        }
コード例 #21
0
        /// <summary>
        /// Previews the image from the scanner with given device id
        /// The preview is allowed only if the selected scanner is equipped with a Flatbed and supports preview.
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="stream">RandomAccessStream in which preview given the by the scan runtime API is kept</param>
        public async void ScanPreview(string deviceId, IRandomAccessStream stream)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Flatbed))
                {
                    if (myScanner.IsPreviewSupported(ImageScannerScanSource.Flatbed))
                    {
                        rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);
                        // Scan API call to get preview from the flatbed
                        var result = await myScanner.ScanPreviewToStreamAsync(ImageScannerScanSource.Flatbed, stream);

                        if (result.Succeeded)
                        {
                            Utils.SetImageSourceFromStream(stream, DisplayImage);
                            rootPage.NotifyUser("Preview scanning is complete. Below is the preview image.", NotifyType.StatusMessage);
                        }
                        else
                        {
                            rootPage.NotifyUser("Failed to preview from Flatbed.", NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        rootPage.NotifyUser("The selected scanner does not support preview from Flatbed.", NotifyType.ErrorMessage);
                    }
                }
                else
                {
                    rootPage.NotifyUser("The selected scanner does not report to be equipped with a Flatbed.", NotifyType.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                Utils.DisplayExceptionErrorMessage(ex);
            }
        }
コード例 #22
0
        /// <summary>
        /// Detecta múltiples tags en una imagen
        /// </summary>
        /// <param name="image">Imagen a procesar</param>
        /// <param name="showProcessedInput">Si se fija a true se muestra el resultado del procesamiento previo que
        /// se realiza antes del proceso de detección de tags</param>
        /// <returns>Lista de tags</returns>
        public static List <Tag> detectTags(System.Drawing.Image image, bool showProcessedInput = false)
        {
            List <Tag> result = new List <Tag>();

            // Procesamos la imagen de entrada
            using (System.Drawing.Image img = image)//prepareInput(image, showProcessedInput))
            {
                using (ImageScanner scanner = new ImageScanner())
                {
                    List <Symbol> symbols = scanner.Scan(img);
                    if (symbols != null && symbols.Count > 0)
                    {
                        // Iteramos los resultados y los transformamos a objetos Tag
                        foreach (Symbol symbol in symbols)
                        {
                            result.Add(new Tag(symbol));
                        }
                    }
                }
            }
            return(result);
        }
コード例 #23
0
        private async void OnScannerAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
        {
            await
            MainPage.Current.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal,
                () =>
            {
                string stuff = "test";

                //MainPage.Current.NotifyUser(String.Format("Scanner with device id {0} has been added", deviceInfo.Id), NotifyType.StatusMessage);

                //// search the device list for a device with a matching device id
                //ScannerDataItem match = FindInList(deviceInfo.Id);

                //// If we found a match then mark it as verified and return
                //if (match != null)
                //{
                //    match.Matched = true;
                //    return;
                //}

                //// Add the new element to the end of the list of devices
                //AppendToList(deviceInfo);
            }
                );

            //var library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
            //var folders = library.Folders;

            StorageFolder testFolder = await StorageFolder.GetFolderFromPathAsync(@"D:\Pictures\Test");

            //ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

            //4D36E967-E325-11CE-BFC1-08002BE10318
            ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceInfo.Id);

            var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Default, testFolder);
        }
コード例 #24
0
        public void ScanCode(System.Drawing.Image image)
        {
            ZBar.ImageScanner scanner = new ImageScanner();
            scanner.Scan(image);
            List <ZBar.Symbol> symbols = new List <Symbol>();

            ZXing.OneD.Code93Reader reader3 = new ZXing.OneD.Code93Reader();
            reader.ResultFound += Reader_ResultFound;
            if (symbols != null && symbols.Count > 0)
            {
                string r = string.Empty;
                foreach (var s in symbols)
                {
                    textBox1.Text = s.Data;
                }
            }
            //ZBar.ImageScanner scanner= new ImageScanner();
            //scanner.SetConfiguration(ZBar.SymbolType.None, ZBar.Config.Enable, 0);
            //scanner.SetConfiguration(ZBar.SymbolType.CODE39, ZBar.Config.Enable, 1);
            //scanner.SetConfiguration(ZBar.SymbolType.CODE128, ZBar.Config.Enable, 1);
            //List<ZBar.Symbol> symbols = new List<Symbol>();
            //symbols = scanner.Scan(image);
            //if (symbols!=null&&symbols.Count>0) {
            //    string result = string.Empty;
            //    foreach (var s in symbols) {
            //        textBox1.Text=s.Data;
            //    }
            //}
            Result result = reader.Decode((Bitmap)image);

            foreach (var point in result.ResultPoints)
            {
                Bitmap bitmap = new Bitmap(image);
                //    panel1.DrawToBitmap(bitmap, new Rectangle(new Point((int)point.X,(int)point.Y), new Size(result.)));
                panel1.BackgroundImage = bitmap;
            }
            textBox1.Text = result.Text;
        }
コード例 #25
0
        private void UpdateDebuff()
        {
            var image = _gameWindowCapturer.GetBitmapFromGameWindow();

            if (image != null)
            {
                using var imageScanner = new ImageScanner(image);

                var debuffs = imageScanner.FindDebuffs();
                if (debuffs != null)
                {
                    var source = ConvertToImageSource(debuffs);
                    PositionWindow(debuffs);
                    DebuffImage.Source = source;
                    debuffs.Dispose();
                    return;
                }
            }

            // Set to 0 size if we don't have anything to show
            DebuffImage.Width  = 0;
            DebuffImage.Height = 0;
        }
コード例 #26
0
        public void Run(string[] args, string tutRoot)
        {
            Help();

            // Default arguments
            // Image digits.png is of dimension 2000x1000
            string imageName     = $"{tutRoot}data\\digits.png";
            string argDivideWith = "10";
            string imageReadType = "";

            if (args.Length == 2)
            {
                imageName     = args[0];
                argDivideWith = args[1];
                imageReadType = "G";
            }
            else if (args.Length == 3)
            {
                imageName     = args[0];
                argDivideWith = args[1];
                imageReadType = args[2];
            }

            Mat I, J;

            try
            {
                if (imageReadType == "G")
                {
                    I = new Mat(imageName, ImreadModes.GrayScale);
                }
                else
                {
                    I = new Mat(imageName, ImreadModes.Color);
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"The image {imageName} could not be found.");
                Cv2.WaitKey();
                return;
            }

            if (I.Empty())
            {
                Console.WriteLine($"The image {imageName} could not be loaded.");
                Cv2.WaitKey();
                return;
            }

            // [divideWith] Create a look-up table based on the divideWith value
            int divideWith = int.Parse(argDivideWith);

            if (divideWith == 0)
            {
                Console.WriteLine("Invalid number entered for dividing.");
                Cv2.WaitKey();
                return;
            }

            byte[] table = new byte[256];
            for (int i = 0; i < 256; ++i)
            {
                table[i] = (byte)(divideWith * (i / divideWith));
            }
            // [divideWith] ================================================

            const int times = 100;
            double    t     = Cv2.GetTickCount();

            for (int i = 0; i < times; ++i)
            {
                Mat clone_i = I.Clone();
                J = ImageScanner.ScanImageAndReduceC(clone_i, table);
            }

            t  = 1000 * (Cv2.GetTickCount() - t) / Cv2.GetTickFrequency();
            t /= times;
            Console.WriteLine($"\nTime of reducing with the C " +
                              $"operator [] (averaged for {times} runs): {t} milliseconds.");

            t = Cv2.GetTickCount();

            for (int i = 0; i < times; ++i)
            {
                Mat clone_i = I.Clone();
                J = ImageScanner.ScanImageAndReduceForEach(clone_i, table);
            }

            t  = 1000 * (Cv2.GetTickCount() - t) / Cv2.GetTickFrequency();
            t /= times;

            Console.WriteLine($"Time of reducing with foreach " +
                              $"(averaged for {times} runs): {t} milliseconds.");

            t = Cv2.GetTickCount();

            for (int i = 0; i < times; ++i)
            {
                Mat clone_i = I.Clone();
                ImageScanner.ScanImageAndReduceRandomAccess(clone_i, table);
            }

            t  = 1000 * (Cv2.GetTickCount() - t) / Cv2.GetTickFrequency();
            t /= times;

            Console.WriteLine($"Time of reducing with the on-the-fly address generation - " +
                              $"at function (averaged for {times} runs): {t} milliseconds.");

            t = Cv2.GetTickCount();

            for (int i = 0; i < times; ++i)
            {
                //! [table-use]
                J = I.LUT(table);
            }
            //! [table-use]

            t  = 1000 * (Cv2.GetTickCount() - t) / Cv2.GetTickFrequency();
            t /= times;

            Console.WriteLine($"Time of reducing with the LUT function " +
                              $"(averaged for {times} runs): {t} milliseconds.");

            Cv2.WaitKey();
        }
コード例 #27
0
 /// <summary> 初始化商品扫描,初始化条码扫描类
 /// </summary>
 public CheckGoods()
 {
     CodeReader = new BarcodeReader();          //初始化ZXing条码扫描类
     CodeReader.Options.CharacterSet = "UTF-8"; //设置条码字符集类型为UTF-8
     CodeReader_2 = new ImageScanner();         //初始化ZBar条码扫描类
 }
コード例 #28
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // CONSTRUCTORS / FACTORIES /////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public DiscoveredScanner(ImageScanner device, string name)
        {
            Device = device;
            Id     = Device.DeviceId;

            Name = name;

            try
            {
                IsAutoAllowed    = device.IsScanSourceSupported(ImageScannerScanSource.AutoConfigured);
                IsFeederAllowed  = device.IsScanSourceSupported(ImageScannerScanSource.Feeder);
                IsFlatbedAllowed = device.IsScanSourceSupported(ImageScannerScanSource.Flatbed);
            }
            catch (Exception exc)
            {
                LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine supported scan sources.");
                throw;
            }

            // auto mode
            if (IsAutoAllowed)
            {
                LogService.Log.Information("DiscoveredScanner: Processing auto mode");
                IsAutoPreviewAllowed = device.IsPreviewSupported(ImageScannerScanSource.AutoConfigured);

                AutoFormats = GenerateFormats(device.AutoConfiguration);
            }

            // flatbed mode
            if (IsFlatbedAllowed)
            {
                LogService.Log.Information("DiscoveredScanner: Processing flatbed mode");
                IsFlatbedColorAllowed      = device.FlatbedConfiguration.IsColorModeSupported(ImageScannerColorMode.Color);
                IsFlatbedGrayscaleAllowed  = device.FlatbedConfiguration.IsColorModeSupported(ImageScannerColorMode.Grayscale);
                IsFlatbedMonochromeAllowed = device.FlatbedConfiguration.IsColorModeSupported(ImageScannerColorMode.Monochrome);
                IsFlatbedAutoColorAllowed  = device.FlatbedConfiguration.IsColorModeSupported(ImageScannerColorMode.AutoColor);

                if (!IsFlatbedColorAllowed && !IsFlatbedGrayscaleAllowed && !IsFlatbedMonochromeAllowed && !IsFlatbedAutoColorAllowed)
                {
                    // no color mode allowed, source mode is invalid
                    IsFlatbedAllowed = false;
                    LogService.Log.Warning("DiscoveredScanner: No color mode for flatbed allowed, invalid source mode");
                }
                else
                {
                    LogService.Log.Information("DiscoveredScanner: Flatbed supports at least one color mode");

                    try
                    {
                        IsFlatbedPreviewAllowed = device.IsPreviewSupported(ImageScannerScanSource.Flatbed);
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine preview support for flatbed.");
                        throw;
                    }

                    try
                    {
                        IsFlatbedAutoCropSingleRegionAllowed = device.FlatbedConfiguration
                                                               .IsAutoCroppingModeSupported(ImageScannerAutoCroppingMode.SingleRegion);
                        IsFlatbedAutoCropMultiRegionAllowed = device.FlatbedConfiguration
                                                              .IsAutoCroppingModeSupported(ImageScannerAutoCroppingMode.MultipleRegion);
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine auto crop support for flatbed.");
                        throw;
                    }

                    FlatbedResolutions = GenerateResolutions(device.FlatbedConfiguration);
                    LogService.Log.Information("Generated {@Resolutions} for flatbed.", FlatbedResolutions);

                    FlatbedFormats = GenerateFormats(device.FlatbedConfiguration);
                    LogService.Log.Information("Generated {@Formats} for feeder.", FlatbedFormats);

                    try
                    {
                        if (device.FlatbedConfiguration.BrightnessStep != 0)
                        {
                            FlatbedBrightnessConfig = GenerateBrightnessConfig(device.FlatbedConfiguration);
                        }
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine BrightnessConfig for flatbed.");
                        throw;
                    }

                    try
                    {
                        if (device.FlatbedConfiguration.ContrastStep != 0)
                        {
                            FlatbedContrastConfig = GenerateContrastConfig(device.FlatbedConfiguration);
                        }
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine ContrastConfig for flatbed.");
                        throw;
                    }
                }
            }

            // feeder mode
            if (IsFeederAllowed)
            {
                LogService.Log.Information("DiscoveredScanner: Processing feeder mode");
                IsFeederColorAllowed      = device.FeederConfiguration.IsColorModeSupported(ImageScannerColorMode.Color);
                IsFeederGrayscaleAllowed  = device.FeederConfiguration.IsColorModeSupported(ImageScannerColorMode.Grayscale);
                IsFeederMonochromeAllowed = device.FeederConfiguration.IsColorModeSupported(ImageScannerColorMode.Monochrome);
                IsFeederAutoColorAllowed  = device.FeederConfiguration.IsColorModeSupported(ImageScannerColorMode.AutoColor);

                if (!IsFeederColorAllowed && !IsFeederGrayscaleAllowed && !IsFeederMonochromeAllowed && !IsFeederAutoColorAllowed)
                {
                    // no color mode allowed, source mode is invalid
                    IsFeederAllowed = false;
                    LogService.Log.Warning("DiscoveredScanner: No color mode for feeder allowed, invalid source mode");
                }
                else
                {
                    LogService.Log.Information("DiscoveredScanner: Feeder supports at least one color mode");

                    try
                    {
                        IsFeederDuplexAllowed = device.FeederConfiguration.CanScanDuplex;
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine duplex support for feeder.");
                        throw;
                    }

                    try
                    {
                        IsFeederPreviewAllowed = device.IsPreviewSupported(ImageScannerScanSource.Feeder);
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine preview support for feeder.");
                        throw;
                    }

                    try
                    {
                        IsFeederAutoCropSingleRegionAllowed = device.FeederConfiguration
                                                              .IsAutoCroppingModeSupported(ImageScannerAutoCroppingMode.SingleRegion);
                        IsFeederAutoCropMultiRegionAllowed = device.FeederConfiguration
                                                             .IsAutoCroppingModeSupported(ImageScannerAutoCroppingMode.MultipleRegion);
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine auto crop support for feeder.");
                        throw;
                    }

                    FeederResolutions = GenerateResolutions(device.FeederConfiguration);
                    LogService.Log.Information("Generated {@Resolutions} for feeder.", FeederResolutions);

                    FeederFormats = GenerateFormats(device.FeederConfiguration);
                    LogService.Log.Information("Generated {@Formats} for feeder.", FeederFormats);

                    try
                    {
                        if (device.FeederConfiguration.BrightnessStep != 0)
                        {
                            FeederBrightnessConfig = GenerateBrightnessConfig(device.FeederConfiguration);
                        }
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine BrightnessConfig for feeder.");
                        throw;
                    }

                    try
                    {
                        if (device.FeederConfiguration.ContrastStep != 0)
                        {
                            FeederContrastConfig = GenerateContrastConfig(device.FeederConfiguration);
                        }
                    }
                    catch (Exception exc)
                    {
                        LogService.Log.Error(exc, "DiscoveredScanner: Couldn't determine ContrastConfig for feeder.");
                        throw;
                    }
                }
            }

            if (!IsAutoAllowed && !IsFlatbedAllowed && !IsFeederAllowed)
            {
                // no source mode allowed, scanner is invalid and useless
                throw new ArgumentException("Scanner doesn't support any source mode and can't be used.");
            }

            LogService.Log.Information("Created {@DiscoveredScanner}", this);
        }
コード例 #29
0
        private static void ConfigureScanner(
            ImageScanner scanner, ImageScannerScanSource source,
            Double hScanPercent, Double vScanPercent)
        {
            if (scanner == null)
            {
                throw new ArgumentNullException("scanner");
            }

            IImageScannerSourceConfiguration sourceConfig = null;
            IImageScannerFormatConfiguration formatConfig = null;

            switch (source)
            {
            case ImageScannerScanSource.Flatbed:
                sourceConfig = scanner.FlatbedConfiguration;
                formatConfig = scanner.FlatbedConfiguration;
                break;

            case ImageScannerScanSource.Feeder:
                sourceConfig = scanner.FeederConfiguration;
                formatConfig = scanner.FeederConfiguration;
                //Additional feeder-specific settings:
                //scanner.FeederConfiguration.CanScanDuplex
                //scanner.FeederConfiguration.Duplex
                //scanner.FeederConfiguration.CanScanAhead
                //scanner.FeederConfiguration.ScanAhead
                //scanner.FeederConfiguration.AutoDetectPageSize
                //scanner.FeederConfiguration.CanAutoDetectPageSize
                //scanner.FeederConfiguration.PageSize
                //scanner.FeederConfiguration.PageSizeDimensions
                //scanner.FeederConfiguration.PageOrientation
                break;

            case ImageScannerScanSource.AutoConfigured:
                formatConfig = scanner.AutoConfiguration;
                break;
            }

            // Potentially update the scanner configuration
            if (sourceConfig != null)
            {
                var maxScanArea = sourceConfig.MaxScanArea; // Size, with Width, Height in Inches    // MinScanArea
                sourceConfig.SelectedScanRegion = new Rect(
                    0,
                    0,
                    maxScanArea.Width * hScanPercent,
                    maxScanArea.Height * vScanPercent); // In inches
                // Additional Configuration settings
                // sourceConfig.AutoCroppingMode
                // sourceConfig.ColorMode ==     // DefaultColorMode
                // sourceConfig.Brightness   // DefaultBrightness    //MaxBrightness     // MinBrightness
                // sourceConfig.Contrast     // DefaultContrast      // MaxContrast      // MinContrast
                // sourceConfig.DesiredResolution = resolution;      // MaxResolution    // MinResolution
                // var actualResolution = sourceConfig.ActualResolution;
            }

            // Potentially update the format that the end product is saved to
            if (formatConfig != null)
            {
                Debug.WriteLine("Default format is {0}", formatConfig.DefaultFormat);

                // NOTE: If your desired format isn't natively supported, it may
                // be possible to generate the desired format post-process
                // using image conversion, etc. libraries.
                var desiredFormats = new[]
                {
                    ImageScannerFormat.Png,
                    ImageScannerFormat.Jpeg,
                    ImageScannerFormat.DeviceIndependentBitmap,
                    //ImageScannerFormat.Tiff,
                    //ImageScannerFormat.Xps,
                    //ImageScannerFormat.OpenXps,
                    //ImageScannerFormat.Pdf
                };

                foreach (var format in desiredFormats)
                {
                    if (formatConfig.IsFormatSupported(format))
                    {
                        formatConfig.Format = format;
                        break;
                    }
                }

                Debug.WriteLine("Configured format is {0}", formatConfig.Format);
            }
        }
コード例 #30
0
        /// <summary>
        /// Scans all the images from Feeder source of the scanner
        /// The scanning of the image is allowed only if the selected scanner has Feeder source
        /// </summary>
        /// <param name="deviceId">scanner device id</param>
        /// <param name="folder">the folder that receives the scanned files</param>
        public async void ScanToFolder(string deviceId, StorageFolder folder)
        {
            try
            {
                // Get the scanner object for this device id
                ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);

                // Check to see if the use has already cancelled the scenario
                if (ModelDataContext.ScenarioRunning)
                {
                    if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Feeder))
                    {
                        // Update Feeder Configuration
                        // Set the scan file format to PNG, if available, if not to DIB
                        if (myScanner.FeederConfiguration.IsFormatSupported(ImageScannerFormat.Png))
                        {
                            myScanner.FeederConfiguration.Format = ImageScannerFormat.Png;
                        }
                        else
                        {
                            myScanner.FeederConfiguration.Format = ImageScannerFormat.DeviceIndependentBitmap;
                        }
                        // Set the color mode to Grayscale, if available
                        if (myScanner.FeederConfiguration.IsColorModeSupported(ImageScannerColorMode.Grayscale))
                        {
                            myScanner.FeederConfiguration.ColorMode = ImageScannerColorMode.Grayscale;
                        }
                        // Set feeder to scan duplex
                        myScanner.FeederConfiguration.Duplex = myScanner.FeederConfiguration.CanScanDuplex;
                        // Set MaxNumberOfPages to zero to scanning all the pages that are present in the feeder
                        myScanner.FeederConfiguration.MaxNumberOfPages = 0;

                        rootPage.NotifyUser("Scanning", NotifyType.StatusMessage);

                        var progress = new Progress <UInt32>(ScanProgress);
                        cancellationToken = new CancellationTokenSource();
                        // Scan API call to start scanning from the Feeder source of the scanner.
                        var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Feeder, folder).AsTask(cancellationToken.Token, progress);

                        ModelDataContext.ScenarioRunning = false;
                        if (result.ScannedFiles.Count > 0)
                        {
                            Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
                            if (result.ScannedFiles.Count > 1)
                            {
                                Utils.UpdateFileListData(result.ScannedFiles, ModelDataContext);
                            }
                        }
                        else
                        {
                            rootPage.NotifyUser("There are no files scanned from the Feeder.", NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        ModelDataContext.ScenarioRunning = false;
                        rootPage.NotifyUser("The selected scanner does not report to be equipped with a Feeder.", NotifyType.ErrorMessage);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Utils.DisplayScanCancelationMessage();
            }
            catch (Exception ex)
            {
                Utils.OnScenarioException(ex, ModelDataContext);
            }
        }