Exemplo n.º 1
0
        protected void SourceFetch(bool isFirst, ScanDirection direction, Range range, object startId = null)
        {
            //Grab data from current connection...
            var set = _db.GetRange(TableNodeColumns(), range, MaxLimit, startId);

            ProcessFetchData(set, isFirst, direction);
        }
Exemplo n.º 2
0
        private void InitVariables()
        {
            scanPixelsDict = new Dictionary <int, string>();
            scanPixelsDict.Add(256, "256x256");
            scanPixelsDict.Add(512, "512x512");
            scanPixelsDict.Add(1024, "1024x1024");
            scanPixelsDict.Add(2048, "2048x2048");
            scanPixelsDict.Add(4096, "4096x4096");

            galvNumDict = new Dictionary <GalvSystem, string>();
            galvNumDict.Add(GalvSystem.TwoGalv, "双振镜");
            galvNumDict.Add(GalvSystem.ThreeGalv, "三振镜");

            scanDirectionDict = new Dictionary <ScanDirection, string>();
            scanDirectionDict.Add(ScanDirection.Single, "单向");
            scanDirectionDict.Add(ScanDirection.Double, "双向");

            galvResponseTime   = DEFAULT_GALV_RESPONSE_TIME;
            fieldSize          = DEFAULT_FIELD_SIZE;
            scanPixels         = DEFAULT_SCAN_PIXELS;
            pixelTime          = DEFAULT_PIXEL_TIME;
            calibrationVoltage = DEFAULT_CALIBRATION_VOLTAGE;
            curveCoff          = DEFAULT_CURVE_COFF;
            galvNum            = DEFAULT_GALV_SYSTEM;
            scanDirection      = DEFAULT_SCAN_DIRECTION;
        }
Exemplo n.º 3
0
        private void ParseDataLine(string line, ScanDirection direction)
        {
            if (string.IsNullOrWhiteSpace(line))
            {
                return;
            }
            char[]   charSeparators = { ';' }; // fields are separated by semicolons
            string[] tokens         = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length != 5)
            {
                return;
            }
            DataMask = long.Parse(tokens[2]);   // the data mask is hopefully always the same
            int      scanLineLength = int.Parse(tokens[1]);
            DateTime timeStamp      = ParseTimeToken(tokens[0]);

            if (direction == ScanDirection.Forward)
            {
                ForwardProfileLengths.Add(scanLineLength);
                forwardTimeStamps.Add(timeStamp);
            }
            if (direction == ScanDirection.Backward)
            {
                BackwardProfileLengths.Add(scanLineLength);
                backwardTimeStamps.Add(timeStamp);
            }
        }
Exemplo n.º 4
0
 private void SelectedIndexChanged(object sender, EventArgs e)
 {
     if (sender.Equals(cbxPixels) && cbxPixels.SelectedItem != null)
     {
         int past = scanPixels;
         scanPixels = ((KeyValuePair <int, string>)cbxPixels.SelectedItem).Key;
         if (past != scanPixels)
         {
             Logger.Info(string.Format("change scan pixels from [{0}] to [{1}].", past, scanPixels));
         }
     }
     else if (sender.Equals(cbxGalvNum) && cbxGalvNum.SelectedItem != null)
     {
         GalvSystem past = galvNum;
         galvNum = ((KeyValuePair <GalvSystem, string>)cbxGalvNum.SelectedItem).Key;
         if (past != galvNum)
         {
             Logger.Info(string.Format("change galv num from [{0}] to [{1}].", past, galvNum));
         }
     }
     else if (sender.Equals(cbxDirection) && cbxDirection.SelectedItem != null)
     {
         ScanDirection past = scanDirection;
         scanDirection = ((KeyValuePair <ScanDirection, string>)cbxDirection.SelectedItem).Key;
         if (scanDirection != past)
         {
             Logger.Info(string.Format("change scan direction from [{0}] to [{1}].", past, scanDirection));
         }
     }
 }
Exemplo n.º 5
0
        public List <string> ScanBitmap(WriteableBitmap bmp, int numscans, ScanDirection direction, BarcodeType types)
        {
            List <string> result = new List <string>();

            Parser parser = new Parser();

            int height = direction == ScanDirection.Horizontal ? bmp.PixelWidth : bmp.PixelHeight;

            if (numscans > height)
            {
                numscans = height; // fix for doing full scan on small images
            }
            for (int i = 0; i < numscans; i++)
            {
                int y1 = (i * height) / numscans;
                int y2 = ((i + 1) * height) / numscans;

                string codesRead = parser.ReadBarcodes(bmp, y1, y2, direction, types);

                if (!string.IsNullOrEmpty(codesRead))
                {
                    result.AddRange(codesRead.Split('|'));
                }
            }
            return(result);
        }
Exemplo n.º 6
0
 private double[] AllProfiles(int column, ScanDirection scanDirection)
 {
     // range checks are performed already
     double[] resultProfile = new double[NumberTotalPoints];
     if (scanDirection == ScanDirection.Forward)
     {
         if (fwdMatrix == null)
         {
             return(InvalidProfileAll());
         }
         for (int i = 0; i < NumberTotalPoints; i++)
         {
             resultProfile[i] = fwdMatrix[column, i];
         }
     }
     if (scanDirection == ScanDirection.Backward)
     {
         if (bwdMatrix == null)
         {
             return(InvalidProfileAll());
         }
         for (int i = 0; i < NumberTotalPoints; i++)
         {
             resultProfile[i] = bwdMatrix[column, i];
         }
         // if profile == XYvec than reverse profile
         if (column == columnNumberOfXYvec)
         {
             Array.Reverse(resultProfile);
         }
     }
     return(resultProfile);
 }
Exemplo n.º 7
0
        private double[] SingleProfile(int column, int profileIndex, ScanDirection scanDirection)
        {
            // range checks are performed already
            double[] resultProfile = new double[scanMetaData.NumberOfDataPoints];
            int      offset        = scanMetaData.NumberOfDataPoints * (profileIndex - 1);

            if (scanDirection == ScanDirection.Forward)
            {
                if (fwdMatrix == null)
                {
                    return(InvalidProfile());
                }
                for (int i = 0; i < scanMetaData.NumberOfDataPoints; i++)
                {
                    resultProfile[i] = fwdMatrix[column, i + offset];
                }
            }
            if (scanDirection == ScanDirection.Backward)
            {
                if (bwdMatrix == null)
                {
                    return(InvalidProfile());
                }
                for (int i = 0; i < scanMetaData.NumberOfDataPoints; i++)
                {
                    resultProfile[i] = bwdMatrix[column, i + offset];
                }
                // if profile == XYvec than reverse profile
                if (column == columnNumberOfXYvec)
                {
                    Array.Reverse(resultProfile);
                }
            }
            return(resultProfile);
        }
Exemplo n.º 8
0
        private void Stack(Program program, Database db, Order order, Order key, TableNode node)
        {
            _key = key;

            OrderColumn column = order.Columns[order.Columns.Count - 1];

            _direction = column.Ascending ? ScanDirection.Forward : ScanDirection.Backward;

            _order = new Order();
            _order.Columns.Add(column);

            _nestedOrder = new Order();
            for (int i = 0; i < order.Columns.Count - 1; i++)
            {
                _nestedOrder.Columns.Add(order.Columns[i]);
            }

            _nestedComparer = new RowComparer(_nestedOrder.Columns[_nestedOrder.Columns.Count - 1], Program.ValueManager);
            _comparer       = new RowComparer(_order.Columns[0], Program.ValueManager);

            if (_nestedOrder.Columns.Count == 1)
            {
                FastoreCursor scan = new FastoreCursor(program, db, node);
                scan.Key        = key;
                scan.Direction  = _nestedOrder.Columns[0].Ascending ? ScanDirection.Forward : ScanDirection.Backward;
                scan.Node.Order = _nestedOrder;
                _nestedTable    = scan;
            }
            else
            {
                _nestedTable = new FastoreStackedCursor(program, db, _nestedOrder, key, node);
            }
        }
Exemplo n.º 9
0
 private void ClearTopographyData(ScanDirection direction)
 {
     double[] invalidDataLine = Enumerable.Repeat(double.NaN, NumberOfColumns).ToArray();
     for (int i = 0; i < NumberTotalPoints; i++)
     {
         InsertDataLineAt(invalidDataLine, i, direction);
     }
 }
Exemplo n.º 10
0
 public TableScan(IValueManager manager, NativeTable table, Schema.Order key, ScanDirection direction, Row firstKey, Row lastKey) : base(manager, table.TableType)
 {
     _nativeTable = table;
     _key         = key;
     _direction   = direction;
     _firstKey    = firstKey;
     _lastKey     = lastKey;
 }
Exemplo n.º 11
0
 /// <remarks> Scan range keys are inclusive. </remarks>
 public Scan(ServerProcess AProcess, TableBuffer ATable, TableBufferIndex AAccessPath, ScanDirection ADirection, Row AFirstKey, Row ALastKey)
 {
     FProcess    = AProcess;
     FTable      = ATable;
     FAccessPath = AAccessPath;
     FDirection  = ADirection;
     FFirstKey   = AFirstKey;
     FLastKey    = ALastKey;
 }
Exemplo n.º 12
0
 /// <remarks> Scan range keys are inclusive. </remarks>
 public Scan(IValueManager manager, NativeTable table, NativeRowTree accessPath, ScanDirection direction, IRow firstKey, IRow lastKey)
 {
     _manager    = manager;
     _table      = table;
     _accessPath = accessPath;
     _direction  = direction;
     _firstKey   = firstKey;
     _lastKey    = lastKey;
 }
Exemplo n.º 13
0
 protected void SourceFetch(bool isFirst, ScanDirection direction)
 {
     SourceFetch
     (
         isFirst,
         direction,
         CreateRange(direction, null, null),
         !isFirst ? GetStartId(direction) : null
     );
 }
Exemplo n.º 14
0
        public async Task ScanAsync(
            string partitionId,
            long indexStart,
            ScanDirection direction,
            Func <long, object, ScanCallbackResult> consume,
            int limit = int.MaxValue)
        {
            SortDefinition <Chunk>   sort;
            FilterDefinition <Chunk> filter;

            if (direction == ScanDirection.Forward)
            {
                sort = Builders <Chunk> .Sort.Ascending(x => x.Index);

                filter = Builders <Chunk> .Filter.And(
                    Builders <Chunk> .Filter.Eq(x => x.PartitionId, partitionId),
                    Builders <Chunk> .Filter.Gte(x => x.Index, indexStart)
                    );
            }
            else
            {
                sort = Builders <Chunk> .Sort.Descending(x => x.Index);

                filter = Builders <Chunk> .Filter.And(
                    Builders <Chunk> .Filter.Eq(x => x.PartitionId, partitionId),
                    Builders <Chunk> .Filter.Lte(x => x.Index, indexStart)
                    );
            }

            var options = new FindOptions <Chunk>()
            {
                Sort = sort
            };

            if (limit != int.MaxValue)
            {
                options.Limit = limit;
            }

            using (var cursor = await _chunks.FindAsync(filter, options))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var b in batch)
                    {
                        if (ScanCallbackResult.Stop == consume(b.Index, b.Payload))
                        {
                            return;
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
 private void UpdateVariables()
 {
     galvResponseTime   = double.Parse(tbxResponseTime.Text);
     fieldSize          = double.Parse(tbxFieldSize.Text);
     scanPixels         = ((KeyValuePair <int, string>)cbxPixels.SelectedItem).Key;
     pixelTime          = double.Parse(tbxPixelTime.Text);
     calibrationVoltage = double.Parse(tbxCalibrationV.Text);
     curveCoff          = double.Parse(tbxCurveCoff.Text);
     galvNum            = ((KeyValuePair <GalvSystem, string>)cbxGalvNum.SelectedItem).Key;
     scanDirection      = ((KeyValuePair <ScanDirection, string>)cbxDirection.SelectedItem).Key;
 }
Exemplo n.º 16
0
        protected Range CreateRange(ScanDirection direction, RangeBound?start, RangeBound?end)
        {
            Range range = new Range();

            range.ColumnID = GetOrderColumnID();

            range.Ascending = direction == ScanDirection.Forward;
            range.Start     = start;
            range.End       = end;

            return(range);
        }
Exemplo n.º 17
0
        private string GetFileName(ScanDirection direction, string extension, int index)
        {
            switch (direction)
            {
            case ScanDirection.Forward:
                return(GetFwdFileName(extension, index));

            case ScanDirection.Backward:
                return(GetBwdFileName(extension, index));

            default:
                return(string.Empty);
            }
        }
Exemplo n.º 18
0
        public async Task ScanStoreAsync(
            long sequenceStart,
            ScanDirection direction,
            Func <long, object, ScanCallbackResult> consume,
            int limit = Int32.MaxValue,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            SortDefinition <Chunk>   sort;
            FilterDefinition <Chunk> filter;

            if (direction == ScanDirection.Forward)
            {
                sort = Builders <Chunk> .Sort.Ascending(x => x.Id);

                filter = Builders <Chunk> .Filter.Gte(x => x.Id, sequenceStart);
            }
            else
            {
                sort = Builders <Chunk> .Sort.Descending(x => x.Id);

                filter = Builders <Chunk> .Filter.Lte(x => x.Id, sequenceStart);
            }

            var options = new FindOptions <Chunk>()
            {
                Sort = sort
            };

            if (limit != int.MaxValue)
            {
                options.Limit = limit;
            }

            using (var cursor = await _chunks.FindAsync(filter, options, cancellationToken))
            {
                while (await cursor.MoveNextAsync(cancellationToken))
                {
                    var batch = cursor.Current;
                    foreach (var b in batch)
                    {
                        if (ScanCallbackResult.Stop == consume(b.Index, b.Payload))
                        {
                            return;
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
 protected object GetStartId(ScanDirection direction)
 {
     // if current buffer direction is forward and a forward range is requested, use the row Id of the last row in the buffer
     // If current buffer direction is forward and a backward range is requested, use the row Id of the first row in the buffer
     // If current buffer direction is backward and a forward range is requested, use the row Id of the first row in the buffer
     // If current buffer direction is backward and a backward range is requested, use the row Id of the last row in the buffer
     if (_bufferDirection == direction)
     {
         return(_buffer[_buffer.Count - 1].ID);
     }
     else
     {
         return(_buffer[0].ID);
     }
 }
        /// <summary>
        /// Updates the User Interface.
        /// </summary>
        public override void UpdateUI()
        {
            _enableSetSettings = false;

            ScanDirection scanDirection = BarcodeReaderSettings.ScanDirection;

            directionLRCheckBox.Checked = (scanDirection & ScanDirection.LeftToRight) != 0;
            directionRLCheckBox.Checked = (scanDirection & ScanDirection.RightToLeft) != 0;
            directionTBCheckBox.Checked = (scanDirection & ScanDirection.TopToBottom) != 0;
            directionBTCheckBox.Checked = (scanDirection & ScanDirection.BottomToTop) != 0;

            directionAngle45CheckBox.Checked = (scanDirection & ScanDirection.Angle45and135) != 0;
            UpdateDirection45();

            _enableSetSettings = true;
        }
Exemplo n.º 21
0
        public void ProcessFetchData(RangeSet fetchData, bool isFirst, ScanDirection direction)
        {
            ClearBuffer();
            SetSourceFlags(fetchData);
            _buffer          = fetchData.Data;
            _bufferDirection = direction;

            //We are always going to point at the start of a new buffer.
            if (_buffer.Count > 0 && !isFirst)
            {
                _bufferIndex = 0;
            }
            else
            {
                _bufferIndex = -1;
            }
        }
Exemplo n.º 22
0
 // This is used to populate the matrices line by line (usually during the file reading)
 public void InsertDataLineAt(double[] dataLine, int position, ScanDirection scanDirection)
 {
     // some range checks
     if (position >= NumberTotalPoints)
     {
         return;
     }
     if (position < 0)
     {
         return;
     }
     if (dataLine == null)
     {
         return;
     }
     if (dataLine.Length != NumberOfColumns)
     {
         return;
     }
     if (scanDirection == ScanDirection.Forward)
     {
         if (fwdMatrix == null)
         {
             return;
         }
         for (int i = 0; i < NumberOfColumns; i++)
         {
             fwdMatrix[i, position] = dataLine[i];
         }
         return;
     }
     if (scanDirection == ScanDirection.Backward)
     {
         if (bwdMatrix == null)
         {
             return;
         }
         for (int i = 0; i < NumberOfColumns; i++)
         {
             bwdMatrix[i, position] = dataLine[i];
         }
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Creates an enumerable object which enumerates all locations within the rectangle
        /// </summary>
        /// <param name="direction">Specifies from which edge the scan should start</param>
        /// <returns>Newly created enumerable object</returns>
        public IEnumerable <MatrixLoc> AsEnumerable(ScanDirection direction)
        {
            switch (direction)
            {
            case ScanDirection.LeftToRight:
                return(GetColumnFirstEnumerator(this.Column, this.LastColumn));

            case ScanDirection.RightToLeft:
                return(GetColumnFirstEnumerator(this.LastColumn - 1, this.Column - 1));

            case ScanDirection.TopToBottom:
                return(GetRowFirstEnumerator(this.Row, this.LastRow));

            case ScanDirection.BottomToTop:
                return(GetRowFirstEnumerator(this.LastRow - 1, this.Row - 1));

            default:
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 24
0
        public Task ScanPartitionAsync(
            string partitionId,
            long fromIndexInclusive,
            ScanDirection direction,
            Func <long, object, ScanCallbackResult> consume,
            long toIndexInclusive = Int64.MaxValue,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            lock (_lock)
            {
                Partition partition;
                if (_partitions.TryGetValue(partitionId, out partition) == false)
                {
                    return(Task.FromResult(0));
                }

                IEnumerable <Chunk> list = partition.Chunks.AsEnumerable();

                if (direction == ScanDirection.Backward)
                {
                    list = list.Reverse();
                }

                list = list.Where(x => x.Index >= fromIndexInclusive && x.Index <= toIndexInclusive);


                foreach (var chunk in list)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (consume(chunk.Index, chunk.Payload) == ScanCallbackResult.Stop)
                    {
                        break;
                    }
                }
            }

            return(Task.FromResult(0));
        }
Exemplo n.º 25
0
        public async Task ScanPartitionAsync(
            string partitionId,
            long fromIndexInclusive,
            ScanDirection direction,
            Func <long, object, ScanCallbackResult> consume,
            long toIndexInclusive = Int64.MaxValue,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var filter = Builders <Chunk> .Filter.And(
                Builders <Chunk> .Filter.Eq(x => x.PartitionId, partitionId),
                Builders <Chunk> .Filter.Gte(x => x.Index, fromIndexInclusive),
                Builders <Chunk> .Filter.Lte(x => x.Index, toIndexInclusive)
                );

            var sort = direction == ScanDirection.Forward
                ? Builders <Chunk> .Sort.Ascending(x => x.Index)
                : Builders <Chunk> .Sort.Descending(x => x.Index);

            var options = new FindOptions <Chunk>()
            {
                Sort = sort
            };

            using (var cursor = await _chunks.FindAsync(filter, options, cancellationToken))
            {
                while (await cursor.MoveNextAsync(cancellationToken))
                {
                    var batch = cursor.Current;
                    foreach (var b in batch)
                    {
                        if (ScanCallbackResult.Stop == consume(b.Index, b.Payload))
                        {
                            return;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Sets the scan direction of reader settings.
        /// </summary>
        private void SetDirection()
        {
            if (!_enableSetSettings)
            {
                return;
            }

            _enableSetSettings = false;

            UpdateDirection45();

            ScanDirection scanDirection = ScanDirection.None;

            if (directionLRCheckBox.Checked)
            {
                scanDirection |= ScanDirection.LeftToRight;
            }
            if (directionRLCheckBox.Checked)
            {
                scanDirection |= ScanDirection.RightToLeft;
            }
            if (directionTBCheckBox.Checked)
            {
                scanDirection |= ScanDirection.TopToBottom;
            }
            if (directionBTCheckBox.Checked)
            {
                scanDirection |= ScanDirection.BottomToTop;
            }
            if (directionAngle45CheckBox.Checked)
            {
                scanDirection |= ScanDirection.Angle45and135;
            }

            BarcodeReaderSettings.ScanDirection = scanDirection;

            _enableSetSettings = true;
        }
Exemplo n.º 27
0
        private void LoadIndexData(string fileName, ScanDirection direction)
        {
            if (!File.Exists(fileName))
            {
                return;
            }
            string       line;
            StreamReader hFile = File.OpenText(fileName);

            // file creation date as a first guess, will be overwritten.
            if (direction == ScanDirection.Forward)
            {
                CreationDate = File.GetCreationTime(fileName);
            }
            while ((line = hFile.ReadLine()) != null)
            {
                ParseDataLine(line, direction);
            }
            if (hFile != null)
            {
                hFile.Close();
            }
        }
Exemplo n.º 28
0
 // this is used for Heydemann correction measures
 // the whole field (= all profiles) must be provided at once
 internal void InsertColumnFor(int columnIndex, double[] field, ScanDirection scanDirection)
 {
     if (columnIndex >= NumberOfColumns)
     {
         return;
     }
     if (columnIndex < 0)
     {
         return;
     }
     if (field.Length != NumberTotalPoints)
     {
         return;
     }
     if (scanDirection == ScanDirection.Forward)
     {
         if (fwdMatrix == null)
         {
             return;
         }
         for (int i = 0; i < field.Length; i++)
         {
             fwdMatrix[columnIndex, i] = field[i];
         }
     }
     if (scanDirection == ScanDirection.Backward)
     {
         if (bwdMatrix == null)
         {
             return;
         }
         for (int i = 0; i < field.Length; i++)
         {
             bwdMatrix[columnIndex, i] = field[i];
         }
     }
 }
Exemplo n.º 29
0
        public Task ScanStoreAsync(
            long sequenceStart,
            ScanDirection direction,
            Func <long, object, ScanCallbackResult> consume,
            int limit = Int32.MaxValue,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            lock (_lock)
            {
                IEnumerable <Chunk> list;
                if (direction == ScanDirection.Forward)
                {
                    list = _chunks.Where(x => x.Id >= sequenceStart)
                           .Take(limit);
                }
                else
                {
                    list = _chunks.ToArray()
                           .Reverse()
                           .Where(x => x.Id <= sequenceStart)
                           .Take(limit);
                }

                foreach (var chunk in list)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    //     Console.WriteLine($"ScanStore {chunk.Id}");
                    if (consume(chunk.Index, chunk.Payload) == ScanCallbackResult.Stop)
                    {
                        break;
                    }
                }
            }

            return(Task.FromResult(0));
        }
        /// <summary>
        /// Initialize BarcodeReader settings.
        /// </summary>
        private void InitReaderSetings()
        {
            // AutomaticRecognition mode
            _reader.Settings.AutomaticRecognition = true;

            // set ScanInterval
            _reader.Settings.ScanInterval = (int)trackBarScanInterval.Value;

            // set ExpectedBarcodes count
            _reader.Settings.ExpectedBarcodes = (int)trackBarExpectedBarcodes.Value;

            // set ScanDicrecion
            ScanDirection scanDirection = ScanDirection.None;

            if (directionLR.IsChecked.Value)
            {
                scanDirection |= ScanDirection.LeftToRight;
            }
            if (directionRL.IsChecked.Value)
            {
                scanDirection |= ScanDirection.RightToLeft;
            }
            if (directionTB.IsChecked.Value)
            {
                scanDirection |= ScanDirection.TopToBottom;
            }
            if (directionBT.IsChecked.Value)
            {
                scanDirection |= ScanDirection.BottomToTop;
            }
            if (directionAngle45.IsChecked.Value)
            {
                scanDirection |= ScanDirection.Angle45and135;
            }
            _reader.Settings.ScanDirection = scanDirection;
        }
Exemplo n.º 31
0
        public List<string> ScanBitmap(WriteableBitmap bmp, int numscans, ScanDirection direction, BarcodeType types)
        {
            List<string> result = new List<string>();

            Parser parser = new Parser();

            int height = direction == ScanDirection.Horizontal ? bmp.PixelWidth : bmp.PixelHeight;

            if (numscans > height)
                numscans = height; // fix for doing full scan on small images
            for (int i = 0; i < numscans; i++)
            {
                int y1 = (i * height) / numscans;
                int y2 = ((i + 1) * height) / numscans;

                string codesRead = parser.ReadBarcodes(bmp, y1, y2, direction, types);

                if (!string.IsNullOrEmpty(codesRead))
                {
                    result.AddRange(codesRead.Split('|'));
                }
            }
            return result;
        }
Exemplo n.º 32
0
        /// <summary>
        /// Scans the active frame in the passed bitmap for barcodes.
        /// </summary>
        /// <param name="CodesRead">Will contain detected barcode strings when the function returns</param>
        /// <param name="bmp">Input bitmap</param>
        /// <param name="numscans">Number of passes that must be made over the page. 
        /// 50 - 100 usually gives a good result.</param>
        /// <param name="direction">Scan direction</param>
        /// <param name="types">Barcode types. Pass BarcodeType.All, or you can specify a list of types,
        /// e.g., BarcodeType.Code39 | BarcodeType.EAN</param>
        public static void ScanPage(ref System.Collections.ArrayList CodesRead, Bitmap bmp, int numscans, ScanDirection direction, BarcodeType types)
        {
            int iHeight, iWidth;
            if (direction == ScanDirection.Horizontal)
            {
                iHeight = bmp.Width;
                iWidth = bmp.Height;
            }
            else
            {
                iHeight = bmp.Height;
                iWidth = bmp.Width;
            }
            if (numscans > iHeight) numscans = iHeight; // fix for doing full scan on small images
            for (int i = 0; i < numscans; i++)
            {
                int y1 = (i * iHeight) / numscans;
                int y2 = ((i + 1) * iHeight) / numscans;
                string sCodesRead = ReadBarcodes(bmp, y1, y2, direction, types);

                if ((sCodesRead != null) && (sCodesRead.Length > 0))
                {
                    string[] asCodes = sCodesRead.Split('|');
                    foreach (string sCode in asCodes)
                    {
                        if (!CodesRead.Contains(sCode))
                            CodesRead.Add(sCode);
                    }
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Scans one band in the passed bitmap for barcodes. 
        /// </summary>
        /// <param name="bmp">Input bitmap</param>
        /// <param name="start">Start coordinate</param>
        /// <param name="end">End coordinate</param>
        /// <param name="direction">
        /// ScanDirection.Vertical: a horizontal band across the page will be examined 
        /// and start,end should be valid y-coordinates.
        /// ScanDirection.Horizontal: a vertical band across the page will be examined 
        /// and start,end should be valid x-coordinates.
        /// </param>
        /// <param name="types">Barcode types to be found</param>
        /// <returns>Pipe-separated list of barcodes, empty string if none were detected</returns>
        public static string ReadBarcodes(Bitmap bmp, int start, int end, ScanDirection direction, BarcodeType types)
        {
            string sBarCodes = "|"; // will hold return values

            // To find a horizontal barcode, find the vertical histogram to find individual barcodes,
            // then get the vertical histogram to decode each
            histogramResult vertHist = verticalHistogram(bmp, start, end, direction);

            // Get the light/dark bar patterns.
            // GetBarPatterns returns the bar pattern in 2 formats:
            //
            //   sbCode39Pattern: for Code39 (only distinguishes narrow bars "n" and wide bars "w")
            //   sbEANPattern: for EAN (distinguishes bar widths 1, 2, 3, 4 and L/G-code)
            //
            StringBuilder sbCode39Pattern;
            StringBuilder sbEANPattern;
            GetBarPatterns(ref vertHist, out sbCode39Pattern, out sbEANPattern);

            // We now have a barcode in terms of narrow & wide bars... Parse it!
            if ((sbCode39Pattern.Length > 0) || (sbEANPattern.Length > 0))
            {
                for (int iPass = 0; iPass < 2; iPass++)
                {
                    if ((types & BarcodeType.Code39) != BarcodeType.None) // if caller wanted Code39
                    {
                        string sCode39 = ParseCode39(sbCode39Pattern);
                        if (sCode39.Length > 0)
                            sBarCodes += sCode39 + "|";
                    }
                    if ((types & BarcodeType.EAN) != BarcodeType.None) // if caller wanted EAN
                    {
                        string sEAN = ParseEAN(sbEANPattern);
                        if (sEAN.Length > 0)
                            sBarCodes += sEAN + "|";
                    }
                    if ((types & BarcodeType.Code128) != BarcodeType.None) // if caller wanted Code128
                    {
                        // Note: Code128 uses same bar width measurement data as EAN
                        string sCode128 = ParseCode128(sbEANPattern);
                        if (sCode128.Length > 0)
                            sBarCodes += sCode128 + "|";
                    }

                    // Reverse the bar pattern arrays to read again in the mirror direction
                    if (iPass == 0)
                    {
                        sbCode39Pattern = ReversePattern(sbCode39Pattern);
                        sbEANPattern = ReversePattern(sbEANPattern);
                    }
                }
            }

            // Return pipe-separated list of found barcodes, if any
            if (sBarCodes.Length > 2)
                return sBarCodes.Substring(1, sBarCodes.Length - 2);
            return string.Empty;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Vertical histogram of an image
        /// </summary>
        /// <param name="bmp">Bitmap</param>
        /// <param name="start">Start coordinate of band to be scanned</param>
        /// <param name="end">End coordinate of band to be scanned</param>
        /// <param name="direction">
        /// ScanDirection.Vertical: start and end denote y-coordinates.
        /// ScanDirection.Horizontal: start and end denote x-coordinates.
        /// </param>
        /// <returns>histogramResult, containing average brightness values across the scan line</returns>
        private static histogramResult verticalHistogram(Bitmap bmp, int start, int end, ScanDirection direction)
        {
            // convert the pixel format of the bitmap to something that we can handle
            PixelFormat pf = CheckSupportedPixelFormat(bmp.PixelFormat);
            BitmapData bmData;
            int xMax, yMax;

            if (direction == ScanDirection.Horizontal)
            {
                bmData = bmp.LockBits(new Rectangle(start, 0, end - start, bmp.Height), ImageLockMode.ReadOnly, pf);
                xMax = bmData.Height;
                yMax = end - start;
            }
            else
            {
                bmData = bmp.LockBits(new Rectangle(0, start, bmp.Width, end - start), ImageLockMode.ReadOnly, pf);
                xMax = bmp.Width;
                yMax = bmData.Height;
            }

            // Create the return value
            byte[] histResult = new byte[xMax + 2]; // add 2 to simulate light-colored background pixels at sart and end of scanline
            ushort[] vertSum = new ushort[xMax];

            unsafe
            {
                byte* p = (byte*)(void*)bmData.Scan0;
                int stride = bmData.Stride;    // stride is offset between horizontal lines in p

                for (int y = 0; y < yMax; ++y)
                {
                    // Add up all the pixel values vertically
                    for (int x = 0; x < xMax; ++x)
                    {
                        if (direction == ScanDirection.Horizontal)
                            vertSum[x] += getpixelbrightness(p, pf, stride, y, x);
                        else
                            vertSum[x] += getpixelbrightness(p, pf, stride, x, y);
                    }
                }
            }
            bmp.UnlockBits(bmData);

            // Now get the average of the row by dividing the pixel by num pixels
            int iDivider = end - start;
            if (pf != PixelFormat.Format1bppIndexed)
                iDivider *= 3;

            byte maxValue = byte.MinValue; // Start the max value at zero
            byte minValue = byte.MaxValue; // Start the min value at the absolute maximum

            for (int i = 1; i <= xMax; i++) // note: intentionally skips first pixel in histResult
            {
                histResult[i] = (byte)(vertSum[i - 1] / iDivider);
                //Save the max value for later
                if (histResult[i] > maxValue) maxValue = histResult[i];
                // Save the min value for later
                if (histResult[i] < minValue) minValue = histResult[i];
            }

            // Set first and last pixel to "white", i.e., maximum intensity
            histResult[0] = maxValue;
            histResult[xMax + 1] = maxValue;

            histogramResult retVal = new histogramResult();
            retVal.histogram = histResult;
            retVal.max = maxValue;
            retVal.min = minValue;

            // Now we have the brightness distribution along the scan band, try to find the distribution of bar widths.
            retVal.threshold = (byte)(minValue + ((maxValue - minValue) >> 1));
            GetBarWidthDistribution(ref retVal, 0, retVal.histogram.Length);

            // Now that we know the narrow bar width, lets look for barcode zones.
            // The image could have more than one barcode in the same band, with
            // different bar widths.
            FindBarcodeZones(ref retVal);
            return retVal;
        }
Exemplo n.º 35
0
 private void btnRunForward_Click(object sender, EventArgs e)
 {
     step = 0;
     appState = ApplicationState.SingleRun;
     rightStep = true;
     if (lastScanDirection == ScanDirection.Left)
     {
         dataPlot.AddNewLockinDataSeries();
     }
     lastScanDirection = ScanDirection.Right;
     if (chkStabilityTest.Checked)
     {
         lockinAmp.SetBufferReadState(LockinAmplifier.BufferedReadCommands.Reset);
         lockinAmp.SetBufferReadState(LockinAmplifier.BufferedReadCommands.Start);
     }
     stageControl.MoveOneStep(rightStep);
     stagePollTimer.Enabled = true;
 }
Exemplo n.º 36
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public CommandStatus Scan(ScanDirection dir, uint lba, ScanType type)
        {
            if (m_logger != null)
            {
                string args = dir.ToString() + ", " + lba.ToString() + ", " + type.ToString();
                m_logger.LogMessage(new UserMessage(UserMessage.Category.Debug, 8, "Bwg.Scsi.Device.Scan(" + args + ")"));
            }

            if (type == ScanType.Reserved)
                throw new Exception("type parameter is of type Reserved");

            using (Command cmd = new Command(ScsiCommandCode.Scan, 12, 0, Command.CmdDirection.None, 10))
            {
                if (dir == ScanDirection.Reverse)
                    cmd.SetCDB8(1, 0x10);
                cmd.SetCDB32(2, lba);
                cmd.SetCDB8(9, (byte)((byte)type << 6));

                CommandStatus st = SendCommand(cmd);
                if (st != CommandStatus.Success)
                    return st;
            }

            return CommandStatus.Success;
        }
Exemplo n.º 37
0
 private static int GetNextIndex(ScanDirection direction, int chunkSize, ref Vector3Int workCoords)
 {
     var x = workCoords.X;
     var y = workCoords.Y;
     var z = workCoords.Z;
     switch (direction)
     {
         case ScanDirection.Xyz:
             workCoords.X = (x + 1)%chunkSize;
             if (workCoords.X < x)
             {
                 workCoords.Y = (y + 1)%chunkSize;
                 if (workCoords.Y < y)
                 {
                     workCoords.Z = (z + 1)%chunkSize;
                 }
             }
             break;
         case ScanDirection.Xzy:
             workCoords.X = (x + 1)%chunkSize;
             if (workCoords.X < x)
             {
                 workCoords.Z = (z + 1)%chunkSize;
                 if (workCoords.Z < z)
                 {
                     workCoords.Y = (y + 1)%chunkSize;
                 }
             }
             break;
         case ScanDirection.Yxz:
             workCoords.Y = (y + 1)%chunkSize;
             if (workCoords.Y < y)
             {
                 workCoords.X = (x + 1)%chunkSize;
                 if (workCoords.X < x)
                 {
                     workCoords.Z = (z + 1)%chunkSize;
                 }
             }
             break;
         case ScanDirection.Yzx:
             workCoords.Y = (y + 1)%chunkSize;
             if (workCoords.Y < y)
             {
                 workCoords.Z = (z + 1) % chunkSize;
                 if (workCoords.Z < z)
                 {
                     workCoords.X = (x + 1) % chunkSize;
                 }
             }
             break;
         case ScanDirection.Zxy:
             workCoords.Z = (z + 1) % chunkSize;
             if (workCoords.Z < z)
             {
                 workCoords.X = (x + 1) % chunkSize;
                 if (workCoords.X < x)
                 {
                     workCoords.Y = (y + 1) % chunkSize;
                 }
             }
             break;
         case ScanDirection.Zyx:
             workCoords.Z = (z + 1) % chunkSize;
             if (workCoords.Z < z)
             {
                 workCoords.Y = (y + 1) % chunkSize;
                 if (workCoords.Y < y)
                 {
                     workCoords.X = (x + 1) % chunkSize;
                 }
             }
             break;
         default:
             throw new ArgumentOutOfRangeException("direction");
     }
     return workCoords.X*chunkSize*chunkSize + workCoords.Z*chunkSize + workCoords.Y;
 }
Exemplo n.º 38
0
 private SortedList<Interval, Block> ConvertArrayToIntervalTreeLinear(Block[] blocks, ScanDirection optimalDirection, out float compressionRatio)
 {
     var count = m_chunkSize * m_chunkSize * m_chunkSize;
     var nodesRemoved = count;
     var intervals = new SortedList<Interval, Block>();
     var min = 0;
     var max = 0;
     var current = Block.Empty;
     var started = false;
     var workCoords = new Vector3Int();
     for (var i = 0; i < count; ++i)
     {
         var block = blocks[GetNextIndex(optimalDirection, m_chunkSize, ref workCoords)];
         if (!(started && block == current))
         {
             if (started)
             {
                 intervals.Add(new Interval((ushort)min, (ushort)max), current);
             }
             current = block;
             min = i;
             started = true;
             --nodesRemoved;
         }
         max = i;
     }
     intervals.Add(new Interval((ushort)min, (ushort)max), current);
     compressionRatio = nodesRemoved / (float)count;
     return intervals;
 }
Exemplo n.º 39
0
 private void EvaluateLinearTree(Block[] blocks, out float compressionRatio, out ScanDirection optimalDirection)
 {
     var count = m_chunkSize * m_chunkSize * m_chunkSize;
     compressionRatio = 0;
     optimalDirection = ScanDirection.Xyz;
     foreach (ScanDirection scanDirection in Enum.GetValues(typeof(ScanDirection)))
     {
         var nodesRemoved = count;
         Block current = Block.Empty;
         Vector3Int workCoords = new Vector3Int();
         for (var i = 0; i < count; ++i)
         {
             var block = blocks[GetNextIndex(scanDirection, m_chunkSize, ref workCoords)];
             if (block == current)
             {
                 continue;
             }
             current = block;
             --nodesRemoved;
         }
         var currentRatio = nodesRemoved / (float)count;
         if (currentRatio <= compressionRatio)
         {
             continue;
         }
         compressionRatio = currentRatio;
         optimalDirection = scanDirection;
         //this means we are mostly air and can just exit out now!
         if (currentRatio > 0.97f)
         {
             break;
         }
     }
 }