Ejemplo n.º 1
0
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         int width = image.Width;
         int height = image.Height;
         int halfWidth = width/2;
         int halfHeight = height/2;

         var topLeft = image.crop(0, 0, halfWidth, halfHeight);
         var result = @delegate.decode(topLeft, hints);
         if (result != null)
            return result;

         var topRight = image.crop(halfWidth, 0, halfWidth, halfHeight);
         result = @delegate.decode(topRight, hints);
         if (result != null)
            return result;

         var bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight);
         result = @delegate.decode(bottomLeft, hints);
         if (result != null)
            return result;

         var bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight);
         result = @delegate.decode(bottomRight, hints);
         if (result != null)
            return result;

         int quarterWidth = halfWidth/2;
         int quarterHeight = halfHeight/2;
         var center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);
         return @delegate.decode(center, hints);
      }
Ejemplo n.º 2
0
      /// <summary>
      /// Locates and decodes a barcode in some format within an image. This method also accepts
      /// hints, each possibly associated to some data, which may help the implementation decode.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result decode(BinaryBitmap image,
                           IDictionary<DecodeHintType, object> hints)
      {
         DecoderResult decoderResult;
         ResultPoint[] points;
         if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
         {
            BitMatrix bits = extractPureBits(image.BlackMatrix);
            if (bits == null)
               return null;
            decoderResult = decoder.decode(bits);
            points = NO_POINTS;
         }
         else
         {
            DetectorResult detectorResult = new Detector(image).detect(hints);
            if (detectorResult == null || detectorResult.Bits == null)
               return null;
            decoderResult = decoder.decode(detectorResult.Bits);
            points = detectorResult.Points;
         }
         if (decoderResult == null)
            return null;

         return new Result(decoderResult.Text, decoderResult.RawBytes, points,
             BarcodeFormat.PDF_417);
      }
Ejemplo n.º 3
0
      /// <summary>
      /// Decodes the multiple.
      /// </summary>
      /// <param name="image">The image.</param>
      /// <param name="hints">The hints.</param>
      /// <returns></returns>
      public Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         var results = new List<Result>();
         var detectorResults = new MultiDetector(image.BlackMatrix).detectMulti(hints);
         foreach (DetectorResult detectorResult in detectorResults)
         {
            var decoderResult = getDecoder().decode(detectorResult.Bits, hints);
            if (decoderResult == null)
               continue;

            var points = detectorResult.Points;
            var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
            var byteSegments = decoderResult.ByteSegments;
            if (byteSegments != null)
            {
               result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
            }
            var ecLevel = decoderResult.ECLevel;
            if (ecLevel != null)
            {
               result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
            }
            results.Add(result);
         }
         return results.Count == 0 ? EMPTY_RESULT_ARRAY : results.ToArray();
      }
Ejemplo n.º 4
0
        public virtual Result decode(BinaryBitmap image, Dictionary<DecodeHintType, Object> hints)
        {
            DecoderResult decoderResult;
            ResultPoint[] points;
            if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
            {
                BitMatrix bits = extractPureBits(image.BlackMatrix);
                decoderResult = decoder.decode(bits);
                points = NO_POINTS;
            }
            else
            {
                DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints);
                decoderResult = decoder.decode(detectorResult.Bits);
                points = detectorResult.Points;
            }

            var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
            if (decoderResult.ByteSegments != null)
            {
                result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments);
            }
            if (decoderResult.ECLevel != null)
            {
                result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString());
            }
            return result;
        }
      private static void assertCorrectImage2result(String path, ExpandedProductParsedResult expected)
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);

         Result theResult = rssExpandedReader.decodeRow(rowNumber, row, null);
         Assert.IsNotNull(theResult);

         Assert.AreEqual(BarcodeFormat.RSS_EXPANDED, theResult.BarcodeFormat);

         ParsedResult result = ResultParser.parseResult(theResult);

         Assert.AreEqual(expected, result);
      }
Ejemplo n.º 6
0
        public virtual Result decode(BinaryBitmap image, System.Collections.Hashtable hints)
        {
            DecoderResult decoderResult;
            ResultPoint[] points;
            if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
            {
                BitMatrix bits = extractPureBits(image.BlackMatrix);
                decoderResult = decoder.decode(bits);
                points = NO_POINTS;
            }
            else
            {
                throw new System.NotImplementedException("Detector(image.BlackMatrix).detect(hints) Not Implemented...");

                //DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints);
                //decoderResult = decoder.decode(detectorResult.Bits);
                //points = detectorResult.Points;
            }

            Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.MICRO_QR_CODE);
            if (decoderResult.ByteSegments != null)
            {
                result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments);
            }
            if (decoderResult.ECLevel != null)
            {
                result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString());
            }
            return result;
        }
Ejemplo n.º 7
0
      /// <summary>
      ///  Locates and decodes a Data Matrix code in an image.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a {@link java.util.Hashtable} from {@link com.google.zxing.DecodeHintType}
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         var blackmatrix = image.BlackMatrix;
         if (blackmatrix == null)
            return null;

         Detector detector = new Detector(blackmatrix);
         ResultPoint[] points = null;
         DecoderResult decoderResult = null;

         var detectorResult = detector.detect(false);
         if (detectorResult != null)
         {
            points = detectorResult.Points;

            decoderResult = new Decoder().decode(detectorResult);
         }
         if (decoderResult == null)
         {
            detectorResult = detector.detect(true);
            if (detectorResult == null)
               return null;
               
            points = detectorResult.Points;
            decoderResult = new Decoder().decode(detectorResult);
            if (decoderResult == null)
               return null;
         }

         if (hints != null &&
             hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
         {
            var rpcb = (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
            if (rpcb != null)
            {
               foreach (var point in points)
               {
                  rpcb(point);
               }
            }
         }

         var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.AZTEC);

         IList<byte[]> byteSegments = decoderResult.ByteSegments;
         if (byteSegments != null)
         {
            result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
         }
         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }

         result.putMetadata(ResultMetadataType.AZTEC_EXTRA_METADATA,
                            new AztecResultMetadata(detectorResult.Compact, detectorResult.NbDatablocks, detectorResult.NbLayers));

         return result;
      }
Ejemplo n.º 8
0
      /// <summary>
      /// Locates and decodes a MaxiCode within an image. This method also accepts
      /// hints, each possibly associated to some data, which may help the implementation decode.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result Decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         DecoderResult decoderResult;
         if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
         {
            BitMatrix bits = extractPureBits(image.BlackMatrix);
            if (bits == null)
               return null;
            decoderResult = decoder.decode(bits, hints);
            if (decoderResult == null)
               return null;
         }
         else
         {
            return null;
         }

         ResultPoint[] points = NO_POINTS;
         Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.MAXICODE);

         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }
         return result;
      }
Ejemplo n.º 9
0
      /// <summary>
      /// Locates and decodes a barcode in some format within an image. This method also accepts
      /// hints, each possibly associated to some data, which may help the implementation decode.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         DecoderResult decoderResult;
         ResultPoint[] points;
         if (image == null || image.BlackMatrix == null)
         {
            // something is wrong with the image
            return null;
         }
         if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
         {
            var bits = extractPureBits(image.BlackMatrix);
            if (bits == null)
               return null;
            decoderResult = decoder.decode(bits, hints);
            points = NO_POINTS;
         }
         else
         {
            var detectorResult = new Detector(image.BlackMatrix).detect(hints);
            if (detectorResult == null)
               return null;
            decoderResult = decoder.decode(detectorResult.Bits, hints);
            points = detectorResult.Points;
         }
         if (decoderResult == null)
            return null;

         // If the code was mirrored: swap the bottom-left and the top-right points.
         var data = decoderResult.Other as QRCodeDecoderMetaData;
         if (data != null)
         {
            data.applyMirroredCorrection(points);
         }

         var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
         var byteSegments = decoderResult.ByteSegments;
         if (byteSegments != null)
         {
            result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
         }
         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }
         if (decoderResult.StructuredAppend)
         {
            result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber);
            result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity);
         }
         return result;
      }
Ejemplo n.º 10
0
 /// <summary>
 /// Locates and decodes a barcode in some format within an image. This method also accepts
 /// hints, each possibly associated to some data, which may help the implementation decode.
 /// **Note** this will return the FIRST barcode discovered if there are many.
 /// </summary>
 /// <param name="image">image of barcode to decode</param>
 /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
 /// to arbitrary data. The
 /// meaning of the data depends upon the hint type. The implementation may or may not do
 /// anything with these hints.</param>
 /// <returns>
 /// String which the barcode encodes
 /// </returns>
 public Result Decode(BinaryBitmap image,
     IDictionary<DecodeHintType, object> hints)
 {
     Result[] results = Decode(image, hints, false);
     if (results.Length == 0)
     {
         return null;
     } else
     {
         return results[0]; // First barcode discovered.
     }
 }
Ejemplo n.º 11
0
        public Result decode(BinaryBitmap image, Dictionary<DecodeHintType, Object> hints)
        {
            int width = image.Width;
            int height = image.Height;
            int halfWidth = width/2;
            int halfHeight = height/2;

            BinaryBitmap topLeft = image.crop(0, 0, halfWidth, halfHeight);
            try
            {
                return delegate_Renamed.decode(topLeft, hints);
            }
            catch (ReaderException)
            {
                // continue
            }

            BinaryBitmap topRight = image.crop(halfWidth, 0, halfWidth, halfHeight);
            try
            {
                return delegate_Renamed.decode(topRight, hints);
            }
            catch (ReaderException)
            {
                // continue
            }

            BinaryBitmap bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight);
            try
            {
                return delegate_Renamed.decode(bottomLeft, hints);
            }
            catch (ReaderException)
            {
                // continue
            }

            BinaryBitmap bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight);
            try
            {
                return delegate_Renamed.decode(bottomRight, hints);
            }
            catch (ReaderException)
            {
                // continue
            }

            int quarterWidth = halfWidth/2;
            int quarterHeight = halfHeight/2;
            BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);
            return delegate_Renamed.decode(center, hints);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
 /// </summary>
 /// <param name="image">Image.</param>
 /// <param name="hints">Hints.</param>
 /// <param name="multiple">If set to <c>true</c> multiple.</param>
 /// <returns><see cref="PDF417DetectorResult"/> encapsulating results of detecting a PDF417 code </returns>
 public static PDF417DetectorResult Detect(BinaryBitmap image,IDictionary<DecodeHintType,object> hints, bool multiple) {
     // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even 
     // different binarizers (SF: or different Skipped Row Counts/Steps?)
     //boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
     
     BitMatrix bitMatrix = image.BlackMatrix;
     
     List<ResultPoint[]> barcodeCoordinates = Detect(multiple, bitMatrix);
     if (barcodeCoordinates.Count == 0) {
         bitMatrix.Rotate180();
         barcodeCoordinates = Detect(multiple, bitMatrix);
     }
     return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);
 }
		public Result[] decodeMultiple(BinaryBitmap image, System.Collections.Hashtable hints)
		{
			System.Collections.ArrayList results = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
			doDecodeMultiple(image, hints, results, 0, 0);
			if ((results.Count == 0))
			{
				throw ReaderException.Instance;
			}
			int numResults = results.Count;
			Result[] resultArray = new Result[numResults];
			for (int i = 0; i < numResults; i++)
			{
				resultArray[i] = (Result) results[i];
			}
			return resultArray;
		}
 /// <summary>
 /// Decodes the multiple.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="hints">The hints.</param>
 /// <returns></returns>
 public Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
 {
    var results = new List<Result>();
    doDecodeMultiple(image, hints, results, 0, 0, 0);
    if ((results.Count == 0))
    {
       return null;
    }
    int numResults = results.Count;
    Result[] resultArray = new Result[numResults];
    for (int i = 0; i < numResults; i++)
    {
       resultArray[i] = (Result)results[i];
    }
    return resultArray;
 }
        public IEnumerable<RecognitionResult> Recognize(BitmapSource bitmap, ZoneConfiguration config)
        {
            var binaryBitmap  = new BinaryBitmap(new HybridBinarizer(new BitmapSourceLuminanceSource(bitmap)));

            var recognizer = Task.Run(() => barcodeReader.Decode(binaryBitmap, new Dictionary<DecodeOptions, object>()))
                .ToObservable();

            var result = recognizer
                .Timeout(TimeSpan.FromSeconds(2))
                .Catch<Result, TimeoutException>(arg => Observable.Return<Result>(null))
                .Catch<Result, NotFoundException>(arg => Observable.Return<Result>(null));

            var text = result.ToTask().Result?.Text;

            yield return new RecognitionResult(text, 1D);
        }
 public Result[] decodeMultiple(BinaryBitmap image, System.Collections.Generic.Dictionary<Object, Object> hints)
 {
     List<Result> results = new List<Result>(10);
     doDecodeMultiple(image, hints, results, 0, 0);
     if ((results.Count == 0))
     {
         throw ReaderException.Instance;
     }
     int numResults = results.Count;
     Result[] resultArray = new Result[numResults];
     for (int i = 0; i < numResults; i++)
     {
         resultArray[i] = (Result) results[i];
     }
     return resultArray;
 }
Ejemplo n.º 17
0
      /// <summary>
      /// Locates and decodes a barcode in some format within an image. This method also accepts
      /// hints, each possibly associated to some data, which may help the implementation decode.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         DecoderResult decoderResult;
         ResultPoint[] points;
         if (image == null || image.BlackMatrix == null)
         {
            // something is wrong with the image
            return null;
         }
         if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
         {
            BitMatrix bits = extractPureBits(image.BlackMatrix);
            if (bits == null)
               return null;
            decoderResult = decoder.decode(bits, hints);
            points = NO_POINTS;
         }
         else
         {
            DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints);
            if (detectorResult == null)
               return null;
            decoderResult = decoder.decode(detectorResult.Bits, hints);
            points = detectorResult.Points;
         }
         if (decoderResult == null)
            return null;

         Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
         IList<byte[]> byteSegments = decoderResult.ByteSegments;
         if (byteSegments != null)
         {
            result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
         }
         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }
         if (decoderResult.StructuredAppend)
         {
            result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber);
            result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity);
         }
         return result;
      }
Ejemplo n.º 18
0
        public Result decode(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            int width      = image.Width;
            int height     = image.Height;
            int halfWidth  = width / 2;
            int halfHeight = height / 2;

            var topLeft = image.crop(0, 0, halfWidth, halfHeight);
            var result  = @delegate.decode(topLeft, hints);

            if (result != null)
            {
                return(result);
            }

            var topRight = image.crop(halfWidth, 0, halfWidth, halfHeight);

            result = @delegate.decode(topRight, hints);
            if (result != null)
            {
                return(result);
            }

            var bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight);

            result = @delegate.decode(bottomLeft, hints);
            if (result != null)
            {
                return(result);
            }

            var bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight);

            result = @delegate.decode(bottomRight, hints);
            if (result != null)
            {
                return(result);
            }

            int quarterWidth  = halfWidth / 2;
            int quarterHeight = halfHeight / 2;
            var center        = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);

            return(@delegate.decode(center, hints));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Decodes the multiple.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="hints">The hints.</param>
        /// <returns></returns>
        public Result[] decodeMultiple(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            var results         = new List <Result>();
            var detectorResults = new MultiDetector(image.BlackMatrix).detectMulti(hints);

            foreach (DetectorResult detectorResult in detectorResults)
            {
                var decoderResult = getDecoder().decode(detectorResult.Bits, hints);
                if (decoderResult == null)
                {
                    continue;
                }

                var points = detectorResult.Points;
                // If the code was mirrored: swap the bottom-left and the top-right points.
                var data = decoderResult.Other as QRCodeDecoderMetaData;
                if (data != null)
                {
                    data.applyMirroredCorrection(points);
                }
                var result       = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
                var byteSegments = decoderResult.ByteSegments;
                if (byteSegments != null)
                {
                    result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
                }
                var ecLevel = decoderResult.ECLevel;
                if (ecLevel != null)
                {
                    result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
                }
                if (decoderResult.StructuredAppend)
                {
                    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber);
                    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity);
                }
                results.Add(result);
            }
            if (results.Count == 0)
            {
                return(null);
            }
            results = ProcessStructuredAppend(results);
            return(results.ToArray());
        }
        /// <summary>
        /// Decodes the multiple.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="hints">The hints.</param>
        /// <returns></returns>
        public Result[] decodeMultiple(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            var results = new List <Result>();

            doDecodeMultiple(image, hints, results, 0, 0, 0);
            if ((results.Count == 0))
            {
                return(null);
            }
            int numResults = results.Count;

            Result[] resultArray = new Result[numResults];
            for (int i = 0; i < numResults; i++)
            {
                resultArray[i] = (Result)results[i];
            }
            return(resultArray);
        }
Ejemplo n.º 21
0
        public BinaryBitmap GetBinaryBitmap(string imageName)
        {
            var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", imageName);

            //Try to find it from the source code folder
            if (!System.IO.File.Exists(fullName))
            {
                fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "Images", imageName);
            }

            var bmp = new System.Drawing.Bitmap(fullName);

            var bin = new ZXing.Common.HybridBinarizer(new RGBLuminanceSource(bmp, bmp.Width, bmp.Height));

            var i = new BinaryBitmap(bin);

            return(i);
        }
Ejemplo n.º 22
0
        static Result ScanWindow(Bitmap screenshot, Rectangle winRect, Rectangle screenRect)
        {
            using (Bitmap window = new Bitmap(winRect.Width, winRect.Height))
            {
                using (Graphics g = Graphics.FromImage(window))
                {
                    g.DrawImage(screenshot, winRect, screenRect, GraphicsUnit.Pixel);
                }

                var binBMP = new BinaryBitmap(
                    new HybridBinarizer(
                        new BitmapLuminanceSource(window)));

                QRCodeReader reader = new QRCodeReader();

                return(reader.decode(binBMP));
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Decoding QR code from saved captured image
        /// </summary>
        private void LF_Image_QRCode_Decode(Mat p_image)
        {
            LuminanceSource source;

            source = new BitmapLuminanceSource(BitmapConverter.ToBitmap(p_image));
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result       result = new MultiFormatReader().decode(bitmap);

            if (result != null)
            {
                string strDecode = result.ToString() + result.BarcodeFormat.ToString();
                mmeQR.Text += strDecode + "\r\n";
            }
            else
            {
                mmeQR.Text += "False" + "\r\n";
            }
        }
Ejemplo n.º 24
0
 private void ScanPreviewBuffer()
 {
     try {
         _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
         var binarizer = new HybridBinarizer(_luminance);
         var binBitmap = new BinaryBitmap(binarizer);
         var result    = _reader.decode(binBitmap);
         if (result != null)
         {
             Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
             var client = new WebClient();
             var sqrl   = new SqrlUrl(result.Text);
             var nonce  = SqrlUtils.CreateClientNonce();
             client.DownloadStringAsync(new Uri(sqrl.GetClientResponse(nonce)));
         }
     } catch {
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
        /// </summary>
        /// <param name="image">Image.</param>
        /// <param name="hints">Hints.</param>
        /// <param name="multiple">If set to <c>true</c> multiple.</param>
        /// <returns><see cref="PDF417DetectorResult"/> encapsulating results of detecting a PDF417 code </returns>
        public static PDF417DetectorResult detect(BinaryBitmap image, IDictionary <DecodeHintType, object> hints, bool multiple)
        {
            // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even
            // different binarizers (SF: or different Skipped Row Counts/Steps?)
            //boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);

            BitMatrix bitMatrix = image.BlackMatrix;

            List <ResultPoint[]> barcodeCoordinates = detect(multiple, bitMatrix);

            if (barcodeCoordinates.Count == 0)
            {
                bitMatrix = (BitMatrix)bitMatrix.Clone();
                bitMatrix.rotate180();
                barcodeCoordinates = detect(multiple, bitMatrix);
            }
            return(new PDF417DetectorResult(bitMatrix, barcodeCoordinates));
        }
Ejemplo n.º 26
0
        static string Read3(string filename)
        {
            QRCodeReader reader = new QRCodeReader();
            Bitmap map = new Bitmap(filename);
            Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            map.Save(stream, ImageFormat.Png);

            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);

            stream.Close();
            LuminanceSource source = new RGBLuminanceSource(data, map.Width, map.Height);
            Binarizer bina = new HybridBinarizer(source);
            BinaryBitmap bMap = new BinaryBitmap(bina);
            Result result = reader.decode(bMap);

            return result.Text;
        }
        public Result[] decodeMultiple(BinaryBitmap image, Hashtable hints)
        {
            var results = new ArrayList();

            doDecodeMultiple(image, hints, results, 0, 0);
            if ((results.Count == 0))
            {
                return(null);
            }
            int numResults = results.Count;

            Result[] resultArray = new Result[numResults];
            for (int i = 0; i < numResults; i++)
            {
                resultArray[i] = (Result)results[i];
            }
            return(resultArray);
        }
Ejemplo n.º 28
0
 public Result decode(BinaryBitmap image, System.Collections.Generic.Dictionary<Object, Object> hints)
 {
     DecoderResult decoderResult;
     ResultPoint[] points;
     if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
     {
         BitMatrix bits = extractPureBits(image);
         decoderResult = decoder.decode(bits);
         points = NO_POINTS;
     }
     else
     {
         DetectorResult detectorResult = new Detector(image).detect();
         decoderResult = decoder.decode(detectorResult.Bits);
         points = detectorResult.Points;
     }
     return new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.PDF417);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Locates and decodes a barcode in some format within an image. This method also accepts
        /// hints, each possibly associated to some data, which may help the implementation decode.
        /// </summary>
        /// <param name="image">image of barcode to decode</param>
        /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
        /// to arbitrary data. The
        /// meaning of the data depends upon the hint type. The implementation may or may not do
        /// anything with these hints.</param>
        /// <returns>
        /// String which the barcode encodes
        /// </returns>
        public Result decode(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            int width      = image.Width;
            int height     = image.Height;
            int halfWidth  = width / 2;
            int halfHeight = height / 2;

            // No need to call makeAbsolute as results will be relative to original top left here
            var result = @delegate.decode(image.crop(0, 0, halfWidth, halfHeight), hints);

            if (result != null)
            {
                return(result);
            }

            result = @delegate.decode(image.crop(halfWidth, 0, halfWidth, halfHeight), hints);
            if (result != null)
            {
                makeAbsolute(result.ResultPoints, halfWidth, 0);
                return(result);
            }

            result = @delegate.decode(image.crop(0, halfHeight, halfWidth, halfHeight), hints);
            if (result != null)
            {
                makeAbsolute(result.ResultPoints, 0, halfHeight);
                return(result);
            }

            result = @delegate.decode(image.crop(halfWidth, halfHeight, halfWidth, halfHeight), hints);
            if (result != null)
            {
                makeAbsolute(result.ResultPoints, halfWidth, halfHeight);
                return(result);
            }

            int quarterWidth  = halfWidth / 2;
            int quarterHeight = halfHeight / 2;
            var center        = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);

            result = @delegate.decode(center, hints);
            makeAbsolute(result.ResultPoints, quarterWidth, quarterHeight);
            return(result);
        }
      public void testFindFinderPatterns()
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         String path = "test/data/blackbox/rssexpanded-1/2.png";

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);
         List<ExpandedPair> previousPairs = new List<ExpandedPair>();

         ExpandedPair pair1 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair1);
         FinderPattern finderPattern = pair1.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(0, finderPattern.Value);

         ExpandedPair pair2 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair2);
         finderPattern = pair2.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(1, finderPattern.Value);

         ExpandedPair pair3 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair3);
         finderPattern = pair3.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(1, finderPattern.Value);

         //   the previous was the last pair
         Assert.IsNull(rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber));
      }
        public void testFindFinderPatterns()
        {
            RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

            String path = "test/data/blackbox/rssexpanded-1/2.png";

            if (!File.Exists(path))
            {
                // Support running from project root too
                path = Path.Combine("..\\..\\..\\Source", path);
            }

#if !SILVERLIGHT
            var image = new Bitmap(Image.FromFile(path));
#else
            var image = new WriteableBitmap(0, 0);
            image.SetSource(File.OpenRead(path));
#endif
            BinaryBitmap        binaryMap     = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
            int                 rowNumber     = binaryMap.Height / 2;
            BitArray            row           = binaryMap.getBlackRow(rowNumber, null);
            List <ExpandedPair> previousPairs = new List <ExpandedPair>();

            ExpandedPair pair1 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
            previousPairs.Add(pair1);
            FinderPattern finderPattern = pair1.FinderPattern;
            Assert.IsNotNull(finderPattern);
            Assert.AreEqual(0, finderPattern.Value);

            ExpandedPair pair2 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
            previousPairs.Add(pair2);
            finderPattern = pair2.FinderPattern;
            Assert.IsNotNull(finderPattern);
            Assert.AreEqual(1, finderPattern.Value);

            ExpandedPair pair3 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
            previousPairs.Add(pair3);
            finderPattern = pair3.FinderPattern;
            Assert.IsNotNull(finderPattern);
            Assert.AreEqual(1, finderPattern.Value);

            //   the previous was the last pair
            Assert.IsNull(rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber));
        }
Ejemplo n.º 32
0
        private void Scaner_Click(object sender, RoutedEventArgs e)
        {
            QrImage.Source = new BitmapImage(new Uri("Scanner.png", UriKind.Relative));
            foreach (Screen screen in Screen.AllScreens)
            {
                using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
                                                     screen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    int maxTry = 10;
                    for (int i = 0; i < maxTry; i++)
                    {
                        int       marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
                        int       marginTop  = (int)((double)fullImage.Height * i / 2.5 / maxTry);
                        Rectangle cropRect   = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
                        Bitmap    target     = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                        using (Graphics g = Graphics.FromImage(target))
                        {
                            g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                                        cropRect,
                                        GraphicsUnit.Pixel);
                        }
                        var          source = new BitmapLuminanceSource(target);
                        var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                        QRCodeReader reader = new QRCodeReader();
                        var          result = reader.decode(bitmap);
                        if (result != null)
                        {
                            //QrImage.Source = Change2Image(target);
                            UrlTextBox.Text = result.ToString();
                        }
                    }
                }
            }
        }
Ejemplo n.º 33
0
 private string DeCodeImg(Bitmap img)
 {
     if (img == null)
     {
         return("");
     }
     #region 将图片转化成 byte数组
     MemoryStream ms = new MemoryStream();
     img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
     byte[] bt = ms.GetBuffer();
     ms.Close();
     #endregion
     LuminanceSource source = new RGBLuminanceSource(bt, img.Width, img.Height);
     BinaryBitmap    bitmap = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source));
     //【1】设置读取条形码规格
     DecodingOptions decodeOption = new DecodingOptions();
     decodeOption.PossibleFormats = new List <BarcodeFormat>()
     {
         BarcodeFormat.EAN_13,
     };
     //【2】进行读取操作
     BarcodeReader br = new BarcodeReader();
     br.Options = decodeOption;
     Result result2, result1;
     try
     {
         //开始解码
         result2 = new MultiFormatReader().decode(bitmap);
         result1 = br.Decode(img);
     }
     catch
     {
         return("");
     }
     if (result1 != null)
     {
         return(result1.Text);
     }
     if (result2 != null)
     {
         return(result2.Text);
     }
     return("");
 }
Ejemplo n.º 34
0
        private static List <BinaryBitmap> ParseBitmaps(Settings settings)
        {
            var files   = Directory.GetFiles(settings.Path, "*.bmp");
            var bitmaps = new List <BinaryBitmap>();

            foreach (var file in files)
            {
                using (var bmp = Bitmap.FromFile(file) as Bitmap)
                {
                    var list   = new List <byte>();
                    var data   = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadOnly, bmp.PixelFormat);
                    var bb     = new BinaryBitmap();
                    var pixels = new byte[data.Height * data.Stride];

                    bitmaps.Add(bb);
                    bb.Size   = bmp.Size;
                    bb.Name   = Path.GetFileNameWithoutExtension(file);
                    bb.Pixels = list;
                    Marshal.Copy(data.Scan0, pixels, 0, pixels.Length);
                    pixels = RemoveExtra(pixels, bb.Size.Width, data.Stride);
                    bmp.UnlockBits(data);

                    var max = pixels.Max();
                    for (int i = 0; i < (pixels.Length / 8) + (pixels.Length % 8 > 0 ? 1 : 0); i++)
                    {
                        byte val = 0;

                        for (int j = 0; j < 8; j++)
                        {
                            if (i * 8 + j > pixels.Length - 1)
                            {
                                break;
                            }

                            val |= (byte)((pixels[i * 8 + j] > max / 2 ? 0 : 1) << (7 - j));
                        }

                        list.Add(val);
                    }
                }
            }

            return(bitmaps);
        }
Ejemplo n.º 35
0
        private string ReadImageAsync(byte[] data)
        {
            try
            {
                var originalImage = BitmapFactory.DecodeByteArray(data, 0, data.Length);

                var source    = new RGBLuminanceSource(data, originalImage.Width, originalImage.Height);
                var reader    = new ZXing.QrCode.QRCodeReader();
                var binarizer = new HybridBinarizer(source);
                var bitmapx   = new BinaryBitmap(binarizer);
                var result    = reader.decode(bitmapx);

                return(result.Text);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 36
0
        //解码操作
        private void button3_Click(object sender, EventArgs e)
        {
            MultiFormatReader mutiReader = new com.google.zxing.MultiFormatReader();
            Bitmap            img        = (Bitmap)Bitmap.FromFile(opFilePath);

            if (img == null)
            {
                return;
            }
            LuminanceSource ls = new RGBLuminanceSource(img, img.Width, img.Height);
            BinaryBitmap    bb = new BinaryBitmap(new com.google.zxing.common.HybridBinarizer(ls));

            Hashtable hints = new Hashtable();

            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            Result r = mutiReader.decode(bb, hints);

            txtMsg.Text = r.Text;
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Scans the camera's preview buffer for a QR code.
        /// </summary>
        private void ScanPreviewBuffer()
        {
            int width  = (int)_camera.PreviewResolution.Width;
            int height = (int)_camera.PreviewResolution.Height;

            byte[] pixelData = new byte[width * height];

            _camera.GetPreviewBufferY(pixelData);

            var luminance = new RGBLuminanceSource(pixelData, width, height, RGBLuminanceSource.BitmapFormat.Gray8);
            var binarizer = new HybridBinarizer(luminance);
            var bitmap    = new BinaryBitmap(binarizer);
            var result    = new QRCodeReader().decode(bitmap);

            if (result != null)
            {
                Dispatcher.BeginInvoke(() => ProcessResult(result));
            }
        }
Ejemplo n.º 38
0
      /// <summary>
      ///  Locates and decodes a Data Matrix code in an image.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a {@link java.util.Hashtable} from {@link com.google.zxing.DecodeHintType}
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result Decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         var blackmatrix = image.BlackMatrix;
         if (blackmatrix == null)
            return null;
         AztecDetectorResult detectorResult = new Detector(blackmatrix).detect();
         if (detectorResult == null)
            return null;

         ResultPoint[] points = detectorResult.Points;

         if (hints != null &&
             hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
         {
            var rpcb = (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
            if (rpcb != null)
            {
               foreach (var point in points)
               {
                  rpcb(point);
               }
            }
         }

         DecoderResult decoderResult = new Internal.Decoder().decode(detectorResult);
         if (decoderResult == null)
            return null;

         Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.AZTEC);

         IList<byte[]> byteSegments = decoderResult.ByteSegments;
         if (byteSegments != null)
         {
            result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
         }
         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }

         return result;
      }
Ejemplo n.º 39
0
        /// <summary>
        ///     Qrs the decoder.
        /// </summary>
        /// <param name="qrCodeFileStream">The qr code file stream.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.Exception">未识别的图片文件</exception>
        public static string QRDecoder(Stream qrCodeFileStream)
        {
            var sKManagedStream = new SKManagedStream(qrCodeFileStream, true);
            var sKBitmap        = SKBitmap.Decode(sKManagedStream);

            sKManagedStream.Dispose();
            if (sKBitmap.IsEmpty)
            {
                sKBitmap.Dispose();
                throw new Exception("未识别的图片文件");
            }

            var w         = sKBitmap.Width;
            var h         = sKBitmap.Height;
            var ps        = w * h;
            var bytes     = new byte[ps * 3];
            var byteIndex = 0;

            for (var x = 0; x < w; x++)
            {
                for (var y = 0; y < h; y++)
                {
                    var color = sKBitmap.GetPixel(x, y);
                    bytes[byteIndex + 0] = color.Red;
                    bytes[byteIndex + 1] = color.Green;
                    bytes[byteIndex + 2] = color.Blue;
                    byteIndex           += 3;
                }
            }

            sKBitmap.Dispose();

            var qRCodeReader       = new QRCodeReader();
            var rGbLuminanceSource = new RGBLuminanceSource(bytes, w, h);
            var hybridBinarizer    = new HybridBinarizer(rGbLuminanceSource);
            var binaryBitmap       = new BinaryBitmap(hybridBinarizer);
            var hints = new Dictionary <DecodeHintType, object> {
                { DecodeHintType.CHARACTER_SET, "utf-8" }
            };
            var result = qRCodeReader.decode(binaryBitmap, hints);

            return(result != null ? result.Text : "");
        }
Ejemplo n.º 40
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException, com.google.zxing.ChecksumException
        public Result decode(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            DecoderResult decoderResult;

            ResultPoint[] points;
            if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
            {
                BitMatrix bits = extractPureBits(image.BlackMatrix);
                decoderResult = decoder.decode(bits);
                points        = NO_POINTS;
            }
            else
            {
                DetectorResult detectorResult = (new Detector(image)).detect();
                decoderResult = decoder.decode(detectorResult.Bits);
                points        = detectorResult.Points;
            }
            return(new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.PDF_417));
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Function for just fetching the QR-Codes in the WebCamTexture-Image.
        /// It stores the Data in a QrCodeData-Object.
        /// It uses the "pixels" field as the image-source, since we can not
        /// access the Unity-API from another thread than the main-thread.
        /// </summary>
        private void DecodeQr()
        {
            while (_runThread)
            {
                // waiting.
                if (_pixels != null)
                {
                    // Create a BitMatrix from the Color32[] of the camear image, so that XZing can detect QR-codes.
                    LuminanceSource lum    = new Color32LuminanceSource(_pixels, GlobalState.Instance.CamWidth, GlobalState.Instance.CamHeight);
                    HybridBinarizer bin    = new HybridBinarizer(lum);
                    BinaryBitmap    binBip = new BinaryBitmap(bin);
                    BitMatrix       matrix = binBip.BlackMatrix;

                    Detector       detector = new Detector(matrix);
                    DetectorResult result   = detector.detect();
                    _qrCodeCollection.UpdateData(result);
                }
            }
        }
Ejemplo n.º 42
0
        public static string ScanQRCodeFromScreen()
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
                                                     screen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    int maxTry = 10;
                    for (int i = 0; i < maxTry; i++)
                    {
                        int       marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
                        int       marginTop  = (int)((double)fullImage.Height * i / 2.5 / maxTry);
                        Rectangle cropRect   = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
                        Bitmap    target     = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                        using (Graphics g = Graphics.FromImage(target))
                        {
                            g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                                        cropRect,
                                        GraphicsUnit.Pixel);
                        }
                        var          source = new BitmapLuminanceSource(target);
                        var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                        QRCodeReader reader = new QRCodeReader();
                        var          result = reader.decode(bitmap);
                        if (result != null)
                        {
                            return(result.Text);
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Gets recipe id
        /// </summary>
        /// <param name="bitmap">QR code bitmap</param>
        /// <returns>recipe id</returns>
        private Task <string> GetRecipeId(Bitmap bitmap)
        {
            return(Task.Run(() =>
            {
                var source = new BitmapLuminanceSource(bitmap);

                var hybridBinarizer = new HybridBinarizer(source);

                var binaryBitmap = new BinaryBitmap(hybridBinarizer);

                var reader = new MultiFormatReader();

                var result = reader.decode(binaryBitmap);

                var id = result?.Text;

                return id;
            }));
        }
Ejemplo n.º 44
0
        private void BarCodeDetectTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                Bitmap             img     = (Bitmap)pictureBox1.Image;
                Reader             reader  = new MultiFormatReader();
                RGBLuminanceSource source1 = new RGBLuminanceSource(img, img.Width, img.Height);
                BinaryBitmap       bitmap  = new BinaryBitmap(new HybridBinarizer(source1));
                Result             result  = reader.decode(bitmap);

                textBox1.Text = result.Text;
                dekodirano    = textBox1.Text;
                BarCodeDetectTimer.Stop();
            }
            catch (Exception)
            {
                statusStrip1.Text = "Greska pri dekodiranju";
            }
        }
Ejemplo n.º 45
0
        private void button1_Click(object sender, EventArgs e)
        {
            QRCodeReader qRCodeReader = new QRCodeReader();

            var bitmapLuminanceSource = new BitmapLuminanceSource((Bitmap)pictureBoxImage.Image);
            GlobalHistogramBinarizer globalHistogramBinarizer = new GlobalHistogramBinarizer(bitmapLuminanceSource);
            BinaryBitmap             binaryBitmap             = new BinaryBitmap(globalHistogramBinarizer);
            Result result = qRCodeReader.decode(binaryBitmap);

            if (result != null)
            {
                textBox2.Text = result.Text;
            }
            else
            {
                MessageBox.Show("无法识别的二维码!");
                textBox2.Text = "";
            }
        }
Ejemplo n.º 46
0
        // Note that we don't try rotation without the try harder flag, even if rotation was supported.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException
        public virtual Result decode(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            try
            {
                return(doDecode(image, hints));
            }
            catch (NotFoundException nfe)
            {
                bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
                if (tryHarder && image.RotateSupported)
                {
                    BinaryBitmap rotatedImage = image.rotateCounterClockwise();
                    Result       result       = doDecode(rotatedImage, hints);
                    // Record that we found it rotated 90 degrees CCW / 270 degrees CW
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: java.util.Map<com.google.zxing.ResultMetadataType,?> metadata = result.getResultMetadata();
                    IDictionary <ResultMetadataType, object> metadata = result.ResultMetadata;
                    int orientation = 270;
                    if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
                    {
                        // But if we found it reversed in doDecode(), add in that result here:
                        orientation = (orientation + (int)metadata[ResultMetadataType.ORIENTATION]) % 360;
                    }
                    result.putMetadata(ResultMetadataType.ORIENTATION, orientation);
                    // Update result points
                    ResultPoint[] points = result.ResultPoints;
                    if (points != null)
                    {
                        int height = rotatedImage.Height;
                        for (int i = 0; i < points.Length; i++)
                        {
                            points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
                        }
                    }
                    return(result);
                }
                else
                {
                    throw nfe;
                }
            }
        }
Ejemplo n.º 47
0
        public void OnPreviewFrame(byte [] bytes, Android.Hardware.Camera camera)
        {
            try {
                byte[] rotatedData = new byte[bytes.Length];
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        rotatedData[x * height + height - y - 1] = bytes[x + y * width];
                    }
                }

                var dataRect = GetFramingRectInPreview();

                var luminance = new YUVLuminanceSource((sbyte[])(Array)rotatedData, width, height, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height());
                var binarized = new BinaryBitmap(new HybridBinarizer(luminance));
                var result    = reader.decodeWithState(binarized);

                //drawResultPoints(binarized, result);

                // an exception would be thrown before this point if the QR code was not detected

                if (string.IsNullOrEmpty(result.Text))
                {
                    return;
                }

                Android.Util.Log.Debug("AEGISSHIELD", "Barcode Found: " + result.Text);
                //ShutdownCamera ();

                ShutdownCamera();

                activity.OnScan(result);
            } catch (ReaderException) {
                Android.Util.Log.Debug("AEGISSHIELD", "No barcode Found");
                // ignore this exception; it happens every time there is a failed scan
            } catch (Exception) {
                // TODO: this one is unexpected.. log or otherwise handle it

                throw;
            }
        }
Ejemplo n.º 48
0
        /*
         * private sbyte HackByteConvert(byte input)
         * {
         *  if (input < 128)
         *  {
         *      return (sbyte) input;
         *  }
         *  else
         *  {
         *      return (sbyte)(127 - input);
         *  }
         * }
         *      sbyte[] sdata = new sbyte[data.Length];
         *      for (int i = 0; i < data.Length; i++)
         *      {
         *          sdata[i] = HackByteConvert(data[i]);
         *      }
         */

        public void OnPreviewFrame(byte[] data, Camera camera)
        {
            if (sentinel)
            {
                return;
            }

            if ((DateTime.UtcNow - lastScanUtc).TotalMilliseconds < 400.0)
            {
                return;
            }

            sentinel = true;
            try
            {
                var size  = camera.GetParameters().PreviewSize;
                var sdata = (sbyte[])(Array)data;
                //Trace.Info("Length w h {0} {1} {2}", data.Length, size.Width, size.Height);
                var source    = new PlanarYUVLuminanceSource(sdata, size.Width, size.Height, 0, 0, size.Width, size.Height, false);
                var binarizer = new HybridBinarizer(source);
                var binBitmap = new BinaryBitmap(binarizer);
                var result    = _reader.decode(binBitmap);
                //Trace.Info("A RESULT {0}", result.Text);
                var t = result.Text;


                this.scanView.ViewModel.Scan(result.Text);

                //LuminanceSource source = new RGBLuminanceSource(data, size.Width, size.Height);
                //BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                //var result = barcodeReader.decode(bitmap);
            }
            catch (Exception exception)
            {
                //Trace.Info("Exception masked - no qr found");// + exception.ToLongString());
            }
            finally
            {
                sentinel    = false;
                lastScanUtc = DateTime.UtcNow;
            }
        }
Ejemplo n.º 49
0
      /// <summary>
      /// Decodes the multiple.
      /// </summary>
      /// <param name="image">The image.</param>
      /// <param name="hints">The hints.</param>
      /// <returns></returns>
      public Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         var results = new List<Result>();
         var detectorResults = new MultiDetector(image.BlackMatrix).detectMulti(hints);
         foreach (DetectorResult detectorResult in detectorResults)
         {
            var decoderResult = getDecoder().decode(detectorResult.Bits, hints);
            if (decoderResult == null)
               continue;

            var points = detectorResult.Points;
            // If the code was mirrored: swap the bottom-left and the top-right points.
            var data = decoderResult.Other as QRCodeDecoderMetaData;
            if (data != null)
            {
               data.applyMirroredCorrection(points);
            }
            var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
            var byteSegments = decoderResult.ByteSegments;
            if (byteSegments != null)
            {
               result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
            }
            var ecLevel = decoderResult.ECLevel;
            if (ecLevel != null)
            {
               result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
            }
            if (decoderResult.StructuredAppend)
            {
               result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber);
               result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity);
            }
            results.Add(result);
         }
         if (results.Count == 0)
         {
            return null;
         }
         results = ProcessStructuredAppend(results);
         return results.ToArray();
      }
Ejemplo n.º 50
0
        public void testMulti()
        {
            // Very basic test for now
            var testBase = AbstractBlackBoxTestCase.buildTestBase("test/data/blackbox/multi-1");

            var source = new BitmapLuminanceSource((Bitmap)Bitmap.FromFile(Path.Combine(testBase, "1.png")));
            var bitmap = new BinaryBitmap(new HybridBinarizer(source));

            var reader  = new GenericMultipleBarcodeReader(new MultiFormatReader());
            var results = reader.decodeMultiple(bitmap);

            Assert.IsNotNull(results);
            Assert.AreEqual(2, results.Length);

            Assert.AreEqual("031415926531", results[0].Text);
            Assert.AreEqual(BarcodeFormat.UPC_A, results[0].BarcodeFormat);

            Assert.AreEqual("www.airtable.com/jobs", results[1].Text);
            Assert.AreEqual(BarcodeFormat.QR_CODE, results[1].BarcodeFormat);
        }
Ejemplo n.º 51
0
        public static Result DecodeScreen()
        {
            // copy screen
            Bitmap bitmapScreen = new Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, PixelFormat.Format32bppArgb);

            using (Graphics graphics = Graphics.FromImage(bitmapScreen))
            {
                graphics.CopyFromScreen(0, 0, 0, 0, bitmapScreen.Size, CopyPixelOperation.SourceCopy);
            }

            BitmapLuminanceSource sourceScreen = new BitmapLuminanceSource(bitmapScreen);
            BinaryBitmap          bitmap       = new BinaryBitmap(new HybridBinarizer(sourceScreen));

            bitmapScreen.Dispose();

            QRCodeReader reader = new QRCodeReader();
            Result       result = reader.decode(bitmap);

            return(result);
        }
Ejemplo n.º 52
0
        public Result[] decodeMultiple(BinaryBitmap image, Dictionary<DecodeHintType, Object> hints)
        {
            var results = new List<Result>(10);

            DetectorResult[] detectorResult = new MultiDetector(image.BlackMatrix).detectMulti(hints);

            foreach (DetectorResult t in detectorResult)
            {
                try
                {
                    DecoderResult decoderResult = Decoder.decode(t.Bits);
                    ResultPoint[] points = t.Points;
                    var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);

                    if (decoderResult.ByteSegments != null)
                    {
                        result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments);
                    }
                    if (decoderResult.ECLevel != null)
                    {
                        result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString());
                    }
                    results.Add(result);
                }
                catch (ReaderException)
                {
                    // ignore and continue 
                }
            }
            if ((results.Count == 0))
            {
                return EMPTY_RESULT_ARRAY;
            }

            var resultArray = new Result[results.Count];
            for (int i = 0; i < results.Count; i++)
            {
                resultArray[i] = (Result) results[i];
            }
            return resultArray;
        }
Ejemplo n.º 53
0
      /// <summary>
      /// Locates and decodes a barcode in some format within an image. This method also accepts
      /// hints, each possibly associated to some data, which may help the implementation decode.
      /// </summary>
      /// <param name="image">image of barcode to decode</param>
      /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
      /// to arbitrary data. The
      /// meaning of the data depends upon the hint type. The implementation may or may not do
      /// anything with these hints.</param>
      /// <returns>
      /// String which the barcode encodes
      /// </returns>
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         int width = image.Width;
         int height = image.Height;
         int halfWidth = width/2;
         int halfHeight = height/2;

         // No need to call makeAbsolute as results will be relative to original top left here
         var result = @delegate.decode(image.crop(0, 0, halfWidth, halfHeight), hints);
         if (result != null)
            return result;

         result = @delegate.decode(image.crop(halfWidth, 0, halfWidth, halfHeight), hints);
         if (result != null)
         {
            makeAbsolute(result.ResultPoints, halfWidth, 0);
            return result;
         }

         result = @delegate.decode(image.crop(0, halfHeight, halfWidth, halfHeight), hints);
         if (result != null)
         {
            makeAbsolute(result.ResultPoints, 0, halfHeight);
            return result;
         }

         result = @delegate.decode(image.crop(halfWidth, halfHeight, halfWidth, halfHeight), hints);
         if (result != null)
         {
            makeAbsolute(result.ResultPoints, halfWidth, halfHeight);
            return result;
         }

         int quarterWidth = halfWidth/2;
         int quarterHeight = halfHeight/2;
         var center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);
         result = @delegate.decode(center, hints);
         makeAbsolute(result.ResultPoints, quarterWidth, quarterHeight);
         return result;
      }
Ejemplo n.º 54
0
 // Note that we don't try rotation without the try harder flag, even if rotation was supported.
 public virtual Result decode(BinaryBitmap image, System.Collections.Generic.Dictionary <Object,Object> hints)
 {
     try
     {
         return doDecode(image, hints);
     }
     catch (ReaderException re)
     {
         bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
         if (tryHarder && image.RotateSupported)
         {
             BinaryBitmap rotatedImage = image.rotateCounterClockwise();
             Result result = doDecode(rotatedImage, hints);
             // Record that we found it rotated 90 degrees CCW / 270 degrees CW
             System.Collections.Generic.Dictionary <Object,Object> metadata = result.ResultMetadata;
             int orientation = 270;
             if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
             {
                 // But if we found it reversed in doDecode(), add in that result here:
                 orientation = (orientation + ((System.Int32) metadata[ResultMetadataType.ORIENTATION])) % 360;
             }
             result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) orientation);
             // Update result points
             ResultPoint[] points = result.ResultPoints;
             int height = rotatedImage.Height;
             for (int i = 0; i < points.Length; i++)
             {
                 points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
             }
             return result;
         }
         else
         {
             throw re;
         }
     }
 }
Ejemplo n.º 55
0
      public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
      {
         DecoderResult decoderResult;
         ResultPoint[] points;
         if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
         {
            BitMatrix bits = extractPureBits(image.BlackMatrix);
            if (bits == null)
               return null;
            decoderResult = decoder.decode(bits);
            points = NO_POINTS;
         }
         else
         {
            DetectorResult detectorResult = new Detector(image.BlackMatrix).detect();
            if (detectorResult == null)
               return null;
            decoderResult = decoder.decode(detectorResult.Bits);
            points = detectorResult.Points;
         }
         if (decoderResult == null)
            return null;

         Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points,
             BarcodeFormat.DATA_MATRIX);
         IList<byte[]> byteSegments = decoderResult.ByteSegments;
         if (byteSegments != null)
         {
            result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
         }
         var ecLevel = decoderResult.ECLevel;
         if (ecLevel != null)
         {
            result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
         }
         return result;
      }
Ejemplo n.º 56
0
 /// <summary>
 /// Locates and decodes a barcode in some format within an image. This method also accepts
 /// hints, each possibly associated to some data, which may help the implementation decode.
 /// Note that we don't try rotation without the try harder flag, even if rotation was supported.
 /// </summary>
 /// <param name="image">image of barcode to decode</param>
 /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
 /// to arbitrary data. The
 /// meaning of the data depends upon the hint type. The implementation may or may not do
 /// anything with these hints.</param>
 /// <returns>
 /// String which the barcode encodes
 /// </returns>
 virtual public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
 {
    var result = doDecode(image, hints);
    if (result == null)
    {
       bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
       bool tryHarderWithoutRotation = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
       if (tryHarder && !tryHarderWithoutRotation && image.RotateSupported)
       {
          BinaryBitmap rotatedImage = image.rotateCounterClockwise();
          result = doDecode(rotatedImage, hints);
          if (result == null)
             return null;
          // Record that we found it rotated 90 degrees CCW / 270 degrees CW
          IDictionary<ResultMetadataType, object> metadata = result.ResultMetadata;
          int orientation = 270;
          if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
          {
             // But if we found it reversed in doDecode(), add in that result here:
             orientation = (orientation +
                            (int) metadata[ResultMetadataType.ORIENTATION])%360;
          }
          result.putMetadata(ResultMetadataType.ORIENTATION, orientation);
          // Update result points
          ResultPoint[] points = result.ResultPoints;
          if (points != null)
          {
             int height = rotatedImage.Height;
             for (int i = 0; i < points.Length; i++)
             {
                points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
             }
          }
       }
    }
    return result;
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Locates and decodes a QR code in an image.
 ///
 /// <returns>a String representing the content encoded by the QR code</returns>
 /// </summary>
 public Result decode(BinaryBitmap image)
 {
    return decode(image, null);
 }
      private void doDecodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints, IList<Result> results, int xOffset, int yOffset, int currentDepth)
      {
         if (currentDepth > MAX_DEPTH)
         {
            return;
         }

         Result result = _delegate.decode(image, hints);
         if (result == null)
            return;

         bool alreadyFound = false;
         for (int i = 0; i < results.Count; i++)
         {
            Result existingResult = (Result)results[i];
            if (existingResult.Text.Equals(result.Text))
            {
               alreadyFound = true;
               break;
            }
         }
         if (!alreadyFound)
         {
            results.Add(translateResultPoints(result, xOffset, yOffset));
         }

         ResultPoint[] resultPoints = result.ResultPoints;
         if (resultPoints == null || resultPoints.Length == 0)
         {
            return;
         }
         int width = image.Width;
         int height = image.Height;
         float minX = width;
         float minY = height;
         float maxX = 0.0f;
         float maxY = 0.0f;
         for (int i = 0; i < resultPoints.Length; i++)
         {
            ResultPoint point = resultPoints[i];
            float x = point.X;
            float y = point.Y;
            if (x < minX)
            {
               minX = x;
            }
            if (y < minY)
            {
               minY = y;
            }
            if (x > maxX)
            {
               maxX = x;
            }
            if (y > maxY)
            {
               maxY = y;
            }
         }

         // Decode left of barcode
         if (minX > MIN_DIMENSION_TO_RECUR)
         {
            doDecodeMultiple(image.crop(0, 0, (int)minX, height), hints, results, xOffset, yOffset, currentDepth + 1);
         }
         // Decode above barcode
         if (minY > MIN_DIMENSION_TO_RECUR)
         {
            doDecodeMultiple(image.crop(0, 0, width, (int)minY), hints, results, xOffset, yOffset, currentDepth + 1);
         }
         // Decode right of barcode
         if (maxX < width - MIN_DIMENSION_TO_RECUR)
         {
            doDecodeMultiple(image.crop((int)maxX, 0, width - (int)maxX, height), hints, results, xOffset + (int)maxX, yOffset, currentDepth + 1);
         }
         // Decode below barcode
         if (maxY < height - MIN_DIMENSION_TO_RECUR)
         {
            doDecodeMultiple(image.crop(0, (int)maxY, width, height - (int)maxY), hints, results, xOffset, yOffset + (int)maxY, currentDepth + 1);
         }
      }
      private static void assertCorrectImage2binary(String path, String expected)
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);

         Assert.IsTrue(rssExpandedReader.decodeRow2pairs(rowNumber, row));

         BitArray binary = BitArrayBuilder.buildBitArray(rssExpandedReader.Pairs);
         Assert.AreEqual(expected, binary.ToString());
      }
Ejemplo n.º 60
0
        /// <summary> This method detects a barcode in a "pure" image -- that is, pure monochrome image
        /// which contains only an unrotated, unskewed, image of a barcode, with some white border
        /// around it. This is a specialized method that works exceptionally fast in this special
        /// case.
        /// </summary>
        private static BitMatrix extractPureBits(BinaryBitmap image)
        {
            // Now need to determine module size in pixels
            BitMatrix matrix = image.BlackMatrix;
            int height = matrix.Height;
            int width = matrix.Width;
            int minDimension = Math.Min(height, width);

            // First, skip white border by tracking diagonally from the top left down and to the right:
            int borderWidth = 0;
            while (borderWidth < minDimension && !matrix.get_Renamed(borderWidth, borderWidth))
            {
                borderWidth++;
            }
            if (borderWidth == minDimension)
            {
                throw ReaderException.Instance;
            }

            // And then keep tracking across the top-left black module to determine module size
            int moduleEnd = borderWidth;
            while (moduleEnd < minDimension && matrix.get_Renamed(moduleEnd, moduleEnd))
            {
                moduleEnd++;
            }
            if (moduleEnd == minDimension)
            {
                throw ReaderException.Instance;
            }

            int moduleSize = moduleEnd - borderWidth;

            // And now find where the rightmost black module on the first row ends
            int rowEndOfSymbol = width - 1;
            while (rowEndOfSymbol >= 0 && !matrix.get_Renamed(rowEndOfSymbol, borderWidth))
            {
                rowEndOfSymbol--;
            }
            if (rowEndOfSymbol < 0)
            {
                throw ReaderException.Instance;
            }
            rowEndOfSymbol++;

            // Make sure width of barcode is a multiple of module size
            if ((rowEndOfSymbol - borderWidth)%moduleSize != 0)
            {
                throw ReaderException.Instance;
            }
            int dimension = (rowEndOfSymbol - borderWidth)/moduleSize;

            // Push in the "border" by half the module width so that we start
            // sampling in the middle of the module. Just in case the image is a
            // little off, this will help recover.
            borderWidth += (moduleSize >> 1);

            int sampleDimension = borderWidth + (dimension - 1)*moduleSize;
            if (sampleDimension >= width || sampleDimension >= height)
            {
                throw ReaderException.Instance;
            }

            // Now just read off the bits
            var bits = new BitMatrix(dimension);
            for (int y = 0; y < dimension; y++)
            {
                int iOffset = borderWidth + y*moduleSize;
                for (int x = 0; x < dimension; x++)
                {
                    if (matrix.get_Renamed(borderWidth + x*moduleSize, iOffset))
                    {
                        bits.set_Renamed(x, y);
                    }
                }
            }
            return bits;
        }