码迷,mamicode.com
首页 > Web开发 > 详细

【开源】ZXING的.NET版本源码解析

时间:2017-02-23 16:17:48      阅读:1191      评论:0      收藏:0      [点我收藏+]

标签:hid   continue   should   .dll   tom   power   info   corners   esb   

[概述]

ZXing ("zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages.

开源地址:

https://github.com/zxing/zxing

[工程结构]

以ZXing.Net.Source.0.14.0.0版本为例,此文件目录下对应两个工程:

Base和WinMD,我们主要分析Base工程,其中:

ZXing.Net.Source.0.14.0.0\Base\Source\lib目录下的工程为源码工程,zxing.vs2012为源码工程Solution文件;

ZXing.Net.Source.0.14.0.0\Base\Clients\WindowsFormsDemo目录下的工程为ZXING输出类库的应用工程,WindowsFormsDemo为应用工程Solution文件。

[应用工程分析]

WindowsFormsDemo有三个Tab,分别为Decoder/Encoder/WebCam,分别实现图片读码/二维码生成/网络摄像头采样读码(主要调用了avicap32.dll,它是Windows API应用程序接口相关模块,用于对摄像头和其它视频硬件进行AⅥ电影和视频的截取,详见工程文件WebCam.cs)。

Decoder(图片读码):

      private void btnStartDecoding_Click(object sender, EventArgs e)
      {
         var fileName = txtBarcodeImageFile.Text;
         if (!File.Exists(fileName))
         {
            MessageBox.Show(this, String.Format("File not found: {0}", fileName), "Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            return;
         }

         using (var bitmap = (Bitmap)Bitmap.FromFile(fileName))
         {
            if (TryOnlyMultipleQRCodes)
               Decode(bitmap, TryMultipleBarcodes, new List<BarcodeFormat> { BarcodeFormat.QR_CODE });
            else
               Decode(bitmap, TryMultipleBarcodes, null);
         }
      }

      private void Decode(Bitmap image, bool tryMultipleBarcodes, IList<BarcodeFormat> possibleFormats)
      {
         resultPoints.Clear();
         lastResults.Clear();
         txtContent.Text = String.Empty;

         var timerStart = DateTime.Now.Ticks;
         Result[] results = null;
         barcodeReader.Options.PossibleFormats = possibleFormats;
         if (tryMultipleBarcodes)
            results = barcodeReader.DecodeMultiple(image);
         else
         {
            var result = barcodeReader.Decode(image);
            if (result != null)
            {
               results = new[] {result};
            }
         }
         var timerStop = DateTime.Now.Ticks;

         if (results == null)
         {
            txtContent.Text = "No barcode recognized";
         }
         labDuration.Text = new TimeSpan(timerStop - timerStart).Milliseconds.ToString("0 ms");

         if (results != null)
         {
            foreach (var result in results)
            {
               if (result.ResultPoints.Length > 0)
               {
                  var rect = new Rectangle((int) result.ResultPoints[0].X, (int) result.ResultPoints[0].Y, 1, 1);
                  foreach (var point in result.ResultPoints)
                  {
                     if (point.X < rect.Left)
                        rect = new Rectangle((int) point.X, rect.Y, rect.Width + rect.X - (int) point.X, rect.Height);
                     if (point.X > rect.Right)
                        rect = new Rectangle(rect.X, rect.Y, rect.Width + (int) point.X - rect.X, rect.Height);
                     if (point.Y < rect.Top)
                        rect = new Rectangle(rect.X, (int) point.Y, rect.Width, rect.Height + rect.Y - (int) point.Y);
                     if (point.Y > rect.Bottom)
                        rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int) point.Y - rect.Y);
                  }
                  using (var g = picBarcode.CreateGraphics())
                  {
                     g.DrawRectangle(Pens.Green, rect);
                  }
               }
            }
         }
      }

Encoder(二维码生成):

(待续)

WebCam(网络摄像头采样读码):

      private void btnDecodeWebCam_Click(object sender, EventArgs e)
      {
         if (wCam == null)
         {
            wCam = new WebCam {Container = picWebCam};

            wCam.OpenConnection();

            webCamTimer = new Timer();
            webCamTimer.Tick += webCamTimer_Tick;
            webCamTimer.Interval = 200; // Image derivation interval
            webCamTimer.Start();

            btnDecodeWebCam.Text = "Decoding..."; // Update UI
         }
         else
         {
            webCamTimer.Stop();
            webCamTimer = null;
            wCam.Dispose();
            wCam = null;

            btnDecodeWebCam.Text = "Decode"; // Update UI
         }
      }

      void webCamTimer_Tick(object sender, EventArgs e)
      {
         var bitmap = wCam.GetCurrentImage(); // Derive a imaghe
         if (bitmap == null)
            return;
         Console.WriteLine("Bitmap width is:{0}, height is{1}. Camera is: {2} mega-pixel.", bitmap.Width, bitmap.Height, bitmap.Width* bitmap.Height/10000);
         var reader = new BarcodeReader();
         var result = reader.Decode(bitmap); // Decode the image
         if (result != null)
         {
            txtTypeWebCam.Text = result.BarcodeFormat.ToString();
            txtContentWebCam.Text = result.Text;
         }
      }

其中WebCam对象定义的各类对摄像头的参数设置和操作详见WebCam.cs。

[源码工程分析]

1.图像解码(Qrcode为例)

Qrcode解码流程为检测定位->解码,涉及的几个主要文件为:BarcodeReader.cs(createBinarizer)->BarcodeReaderGeneric.cs(createBinarizer)->HybridBinarizer.cs(createBinarizer)、QRCodeReader.cs,Detector.cs和FinderPatternFinder.cs,Decoder.cs。

HybridBinarizer.cs(createBinarizer)类实现位图的二值化处理,核心代码段为:

      /// <summary>
      /// Calculates the final BitMatrix once for all requests. This could be called once from the
      /// constructor instead, but there are some advantages to doing it lazily, such as making
      /// profiling easier, and not doing heavy lifting when callers don‘t expect it.
      /// </summary>
      private void binarizeEntireImage()
      {
         if (matrix == null)
         {
            LuminanceSource source = LuminanceSource;
            int width = source.Width;
            int height = source.Height;
            if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION)
            {
               byte[] luminances = source.Matrix;

               int subWidth = width >> BLOCK_SIZE_POWER;
               if ((width & BLOCK_SIZE_MASK) != 0)
               {
                  subWidth++;
               }
               int subHeight = height >> BLOCK_SIZE_POWER;
               if ((height & BLOCK_SIZE_MASK) != 0)
               {
                  subHeight++;
               }
               int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height);

               var newMatrix = new BitMatrix(width, height);
               calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);
               matrix = newMatrix;
            }
            else
            {
               // If the image is too small, fall back to the global histogram approach.
               matrix = base.BlackMatrix;
            }
         }
      }

      /// <summary>
      /// For each 8x8 block in the image, calculate the average black point using a 5x5 grid
      /// of the blocks around it. Also handles the corner cases (fractional blocks are computed based
      /// on the last 8 pixels in the row/column which are also used in the previous block).
      /// PS(Jay):This algrithm has big issue!!! Should be enhanced!!!
      /// </summary>
      /// <param name="luminances">The luminances.</param>
      /// <param name="subWidth">Width of the sub.</param>
      /// <param name="subHeight">Height of the sub.</param>
      /// <param name="width">The width.</param>
      /// <param name="height">The height.</param>
      /// <param name="blackPoints">The black points.</param>
      /// <param name="matrix">The matrix.</param>
      private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight, int width, int height, int[][] blackPoints, BitMatrix matrix)
      {
         for (int y = 0; y < subHeight; y++)
         {
            int yoffset = y << BLOCK_SIZE_POWER;
            int maxYOffset = height - BLOCK_SIZE;
            if (yoffset > maxYOffset)
            {
               yoffset = maxYOffset;
            }
            for (int x = 0; x < subWidth; x++)
            {
               int xoffset = x << BLOCK_SIZE_POWER;
               int maxXOffset = width - BLOCK_SIZE;
               if (xoffset > maxXOffset)
               {
                  xoffset = maxXOffset;
               }
               int left = cap(x, 2, subWidth - 3);
               int top = cap(y, 2, subHeight - 3);
               int sum = 0;
               for (int z = -2; z <= 2; z++)
               {
                  int[] blackRow = blackPoints[top + z];
                  sum += blackRow[left - 2];
                  sum += blackRow[left - 1];
                  sum += blackRow[left];
                  sum += blackRow[left + 1];
                  sum += blackRow[left + 2];
               }
               int average = sum / 25;
               thresholdBlock(luminances, xoffset, yoffset, average, width, matrix);
            }
         }
      }

      private static int cap(int value, int min, int max)
      {
         return value < min ? min : value > max ? max : value;
      }

      /// <summary>
      /// Applies a single threshold to an 8x8 block of pixels.
      /// </summary>
      /// <param name="luminances">The luminances.</param>
      /// <param name="xoffset">The xoffset.</param>
      /// <param name="yoffset">The yoffset.</param>
      /// <param name="threshold">The threshold.</param>
      /// <param name="stride">The stride.</param>
      /// <param name="matrix">The matrix.</param>
      private static void thresholdBlock(byte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix)
      {
         int offset = (yoffset * stride) + xoffset;
         for (int y = 0; y < BLOCK_SIZE; y++, offset += stride)
         {
            for (int x = 0; x < BLOCK_SIZE; x++)
            {
               int pixel = luminances[offset + x] & 0xff;
               // Comparison needs to be <=, so that black == 0 pixels are black, even if the threshold is 0.
               matrix[xoffset + x, yoffset + y] = (pixel <= threshold);
            }
         }
      }

      /// <summary>
      /// Calculates a single black point for each 8x8 block of pixels and saves it away.
      /// See the following thread for a discussion of this algorithm:
      /// http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
      /// </summary>
      /// <param name="luminances">The luminances.</param>
      /// <param name="subWidth">Width of the sub.</param>
      /// <param name="subHeight">Height of the sub.</param>
      /// <param name="width">The width.</param>
      /// <param name="height">The height.</param>
      /// <returns></returns>
      private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight, int width, int height)
      {
         int[][] blackPoints = new int[subHeight][];
         for (int i = 0; i < subHeight; i++)
         {
            blackPoints[i] = new int[subWidth];
         }

         for (int y = 0; y < subHeight; y++)
         {
            int yoffset = y << BLOCK_SIZE_POWER;
            int maxYOffset = height - BLOCK_SIZE;
            if (yoffset > maxYOffset)
            {
               yoffset = maxYOffset;
            }
            for (int x = 0; x < subWidth; x++)
            {
               int xoffset = x << BLOCK_SIZE_POWER;
               int maxXOffset = width - BLOCK_SIZE;
               if (xoffset > maxXOffset)
               {
                  xoffset = maxXOffset;
               }
               int sum = 0;
               int min = 0xFF;
               int max = 0;
               for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width)
               {
                  for (int xx = 0; xx < BLOCK_SIZE; xx++)
                  {
                     int pixel = luminances[offset + xx] & 0xFF;
                     // still looking for good contrast
                     sum += pixel;
                     if (pixel < min)
                     {
                        min = pixel;
                     }
                     if (pixel > max)
                     {
                        max = pixel;
                     }
                  }
                  // short-circuit min/max tests once dynamic range is met
                  if (max - min > MIN_DYNAMIC_RANGE)
                  {
                     // finish the rest of the rows quickly
                     for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width)
                     {
                        for (int xx = 0; xx < BLOCK_SIZE; xx++)
                        {
                           sum += luminances[offset + xx] & 0xFF;
                        }
                     }
                  }
               }

               // The default estimate is the average of the values in the block.
               int average = sum >> (BLOCK_SIZE_POWER * 2);
               if (max - min <= MIN_DYNAMIC_RANGE)
               {
                  // If variation within the block is low, assume this is a block with only light or only
                  // dark pixels. In that case we do not want to use the average, as it would divide this
                  // low contrast area into black and white pixels, essentially creating data out of noise.
                  //
                  // The default assumption is that the block is light/background. Since no estimate for
                  // the level of dark pixels exists locally, use half the min for the block.
                  average = min >> 1;

                  if (y > 0 && x > 0)
                  {
                     // Correct the "white background" assumption for blocks that have neighbors by comparing
                     // the pixels in this block to the previously calculated black points. This is based on
                     // the fact that dark barcode symbology is always surrounded by some amount of light
                     // background for which reasonable black point estimates were made. The bp estimated at
                     // the boundaries is used for the interior.

                     // The (min < bp) is arbitrary but works better than other heuristics that were tried.
                     int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) +
                         blackPoints[y - 1][x - 1]) >> 2;
                     if (min < averageNeighborBlackPoint)
                     {
                        average = averageNeighborBlackPoint;
                     }
                  }
               }
               blackPoints[y][x] = average;
            }
         }
         return blackPoints;
      }

这一段算法有存在改进的必要。在HybridBinarizer继承的GlobalHistogramBinarizer类中,是从图像中均匀取5行(覆盖整个图像高度),每行取中间五分之四作为样本;以灰度值为X轴,每个灰度值的像素个数为Y轴建立一个直方图,从直方图中取点数最多的一个灰度值,然后再去给其他的灰度值进行分数计算,按照点数乘以与最多点数灰度值的距离的平方来进行打分,选分数最高的一个灰度值。接下来在这两个灰度值中间选取一个区分界限,取的原则是尽量靠近中间并且要点数越少越好。界限有了以后就容易了,与整幅图像的每个点进行比较,如果灰度值比界限小的就是黑,在新的矩阵中将该点置1,其余的就是白,为0。此部分具体代码见GlobalHistogramBinarizer类的BlackMatrix()重写方法。这个算法的劣势是由于是全局计算阈值点,所以应对局部阴影不太理想(However, because it picks a global black point, it cannot handle difficult shadows and gradients.)。

 

QRCodeReader类实现了接口Reader,核心段代码为:

      /// <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)) // 纯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); // 检测barcode
            if (detectorResult == null)
               return null;
            decoderResult = decoder.decode(detectorResult.Bits, hints); // 解码barcode
            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;
      }

 

qrcode->detector目录下的Detector类:

namespace ZXing.QrCode.Internal
{
   /// <summary>
   /// <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
   /// is rotated or skewed, or partially obscured.</p>
   /// </summary>
   /// <author>Sean Owen</author>
   public class Detector
   {
      private readonly BitMatrix image;
      private ResultPointCallback resultPointCallback;

      /// <summary>
      /// Initializes a new instance of the <see cref="Detector"/> class.
      /// </summary>
      /// <param name="image">The image.</param>
      public Detector(BitMatrix image)
      {
         this.image = image;
      }

      /// <summary>
      /// Gets the image.
      /// </summary>
      virtual protected internal BitMatrix Image
      {
         get
         {
            return image;
         }
      }

      /// <summary>
      /// Gets the result point callback.
      /// </summary>
      virtual protected internal ResultPointCallback ResultPointCallback
      {
         get
         {
            return resultPointCallback;
         }
      }

      /// <summary>
      ///   <p>Detects a QR Code in an image, simply.</p>
      /// </summary>
      /// <returns>
      ///   <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
      /// </returns>
      public virtual DetectorResult detect()
      {
         return detect(null);
      }

      /// <summary>
      ///   <p>Detects a QR Code in an image, simply.</p>
      /// </summary>
      /// <param name="hints">optional hints to detector</param>
      /// <returns>
      ///   <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
      /// </returns>
      public virtual DetectorResult detect(IDictionary<DecodeHintType, object> hints)
      {
         resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];

         FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
         FinderPatternInfo info = finder.find(hints);
         if (info == null)
            return null;

         return processFinderPatternInfo(info);
      }

      /// <summary>
      /// Processes the finder pattern info.
      /// </summary>
      /// <param name="info">The info.</param>
      /// <returns></returns>
      protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info)
      {
         FinderPattern topLeft = info.TopLeft;
         FinderPattern topRight = info.TopRight;
         FinderPattern bottomLeft = info.BottomLeft;

         float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
         if (moduleSize < 1.0f)
         {
            return null;
         }
         int dimension;
         if (!computeDimension(topLeft, topRight, bottomLeft, moduleSize, out dimension))
            return null;
         Internal.Version provisionalVersion = Internal.Version.getProvisionalVersionForDimension(dimension);
         if (provisionalVersion == null)
            return null;
         int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7;

         AlignmentPattern alignmentPattern = null;
         // Anything above version 1 has an alignment pattern
         if (provisionalVersion.AlignmentPatternCenters.Length > 0)
         {

            // Guess where a "bottom right" finder pattern would have been
            float bottomRightX = topRight.X - topLeft.X + bottomLeft.X;
            float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y;

            // Estimate that alignment pattern is closer by 3 modules
            // from "bottom right" to known top left location
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            float correctionToTopLeft = 1.0f - 3.0f / (float)modulesBetweenFPCenters;
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            int estAlignmentX = (int)(topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X));
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            int estAlignmentY = (int)(topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y));

            // Kind of arbitrary -- expand search radius before giving up
            for (int i = 4; i <= 16; i <<= 1)
            {
               alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float)i);
               if (alignmentPattern == null)
                  continue;
               break;
            }
            // If we didn‘t find alignment pattern... well try anyway without it
         }

         PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);

         BitMatrix bits = sampleGrid(image, transform, dimension);
         if (bits == null)
            return null;

         ResultPoint[] points;
         if (alignmentPattern == null)
         {
            points = new ResultPoint[] { bottomLeft, topLeft, topRight };
         }
         else
         {
            points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern };
         }
         return new DetectorResult(bits, points);
      }

      private static PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension)
      {
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         float dimMinusThree = (float)dimension - 3.5f;
         float bottomRightX;
         float bottomRightY;
         float sourceBottomRightX;
         float sourceBottomRightY;
         if (alignmentPattern != null)
         {
            bottomRightX = alignmentPattern.X;
            bottomRightY = alignmentPattern.Y;
            sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f;
         }
         else
         {
            // Don‘t have an alignment pattern, just make up the bottom-right point
            bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X;
            bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y;
            sourceBottomRightX = sourceBottomRightY = dimMinusThree;
         }

         return PerspectiveTransform.quadrilateralToQuadrilateral(
            3.5f,
            3.5f,
            dimMinusThree,
            3.5f,
            sourceBottomRightX,
            sourceBottomRightY,
            3.5f,
            dimMinusThree,
            topLeft.X,
            topLeft.Y,
            topRight.X,
            topRight.Y,
            bottomRightX,
            bottomRightY,
            bottomLeft.X,
            bottomLeft.Y);
      }

      private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension)
      {
         GridSampler sampler = GridSampler.Instance;
         return sampler.sampleGrid(image, dimension, dimension, transform);
      }

      /// <summary> <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
      /// of the finder patterns and estimated module size.</p>
      /// </summary>
      private static bool computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize, out int dimension)
      {
         int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
         int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
         dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
         switch (dimension & 0x03)
         {
            // mod 4
            case 0:
               dimension++;
               break;
            // 1? do nothing
            case 2:
               dimension--;
               break;
            case 3:
               return true;
         }
         return true;
      }

      /// <summary> <p>Computes an average estimated module size based on estimated derived from the positions
      /// of the three finder patterns.</p>
      /// </summary>
      protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft)
      {
         // Take the average
         return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
      }

      /// <summary> <p>Estimates module size based on two finder patterns -- it uses
      /// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
      /// width of each, measuring along the axis between their centers.</p>
      /// </summary>
      private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern)
      {
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int)pattern.X, (int)pattern.Y, (int)otherPattern.X, (int)otherPattern.Y);
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int)otherPattern.X, (int)otherPattern.Y, (int)pattern.X, (int)pattern.Y);
         if (Single.IsNaN(moduleSizeEst1))
         {
            return moduleSizeEst2 / 7.0f;
         }
         if (Single.IsNaN(moduleSizeEst2))
         {
            return moduleSizeEst1 / 7.0f;
         }
         // Average them, and divide by 7 since we‘ve counted the width of 3 black modules,
         // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
         return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
      }

      /// <summary> See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
      /// a finder pattern by looking for a black-white-black run from the center in the direction
      /// of another point (another finder pattern center), and in the opposite direction too.
      /// </summary>
      private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY)
      {

         float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);

         // Now count other way -- don‘t run off image though of course
         float scale = 1.0f;
         int otherToX = fromX - (toX - fromX);
         if (otherToX < 0)
         {
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            scale = (float)fromX / (float)(fromX - otherToX);
            otherToX = 0;
         }
         else if (otherToX >= image.Width)
         {
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            scale = (float)(image.Width - 1 - fromX) / (float)(otherToX - fromX);
            otherToX = image.Width - 1;
         }
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         int otherToY = (int)(fromY - (toY - fromY) * scale);

         scale = 1.0f;
         if (otherToY < 0)
         {
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            scale = (float)fromY / (float)(fromY - otherToY);
            otherToY = 0;
         }
         else if (otherToY >= image.Height)
         {
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
            scale = (float)(image.Height - 1 - fromY) / (float)(otherToY - fromY);
            otherToY = image.Height - 1;
         }
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         otherToX = (int)(fromX + (otherToX - fromX) * scale);

         result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
         return result - 1.0f; // -1 because we counted the middle pixel twice
      }

      /// <summary> <p>This method traces a line from a point in the image, in the direction towards another point.
      /// It begins in a black region, and keeps going until it finds white, then black, then white again.
      /// It reports the distance from the start to this point.</p>
      /// 
      /// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
      /// may be skewed or rotated.</p>
      /// </summary>
      private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY)
      {
         // Mild variant of Bresenham‘s algorithm;
         // see http://en.wikipedia.org/wiki/Bresenham‘s_line_algorithm
         bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX);
         if (steep)
         {
            int temp = fromX;
            fromX = fromY;
            fromY = temp;
            temp = toX;
            toX = toY;
            toY = temp;
         }

         int dx = Math.Abs(toX - fromX);
         int dy = Math.Abs(toY - fromY);
         int error = -dx >> 1;
         int xstep = fromX < toX ? 1 : -1;
         int ystep = fromY < toY ? 1 : -1;

         // In black pixels, looking for white, first or second time.
         int state = 0;
         // Loop up until x == toX, but not beyond
         int xLimit = toX + xstep;
         for (int x = fromX, y = fromY; x != xLimit; x += xstep)
         {
            int realX = steep ? y : x;
            int realY = steep ? x : y;

            // Does current pixel mean we have moved white to black or vice versa?
            // Scanning black in state 0,2 and white in state 1, so if we find the wrong
            // color, advance to next state or end if we are in state 2 already
            if ((state == 1) == image[realX, realY])
            {
               if (state == 2)
               {
                  return MathUtils.distance(x, y, fromX, fromY);
               }
               state++;
            }
            error += dy;
            if (error > 0)
            {
               if (y == toY)
               {


                  break;
               }
               y += ystep;
               error -= dx;
            }
         }
         // Found black-white-black; give the benefit of the doubt that the next pixel outside the image
         // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
         // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
         if (state == 2)
         {
            return MathUtils.distance(toX + xstep, toY, fromX, fromY);
         }
         // else we didn‘t find even black-white-black; no estimate is really possible
         return Single.NaN;

      }

      /// <summary>
      ///   <p>Attempts to locate an alignment pattern in a limited region of the image, which is
      /// guessed to contain it. This method uses {@link AlignmentPattern}.</p>
      /// </summary>
      /// <param name="overallEstModuleSize">estimated module size so far</param>
      /// <param name="estAlignmentX">x coordinate of center of area probably containing alignment pattern</param>
      /// <param name="estAlignmentY">y coordinate of above</param>
      /// <param name="allowanceFactor">number of pixels in all directions to search from the center</param>
      /// <returns>
      ///   <see cref="AlignmentPattern"/> if found, or null otherwise
      /// </returns>
      protected AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor)
      {
         // Look for an alignment pattern (3 modules in size) around where it
         // should be
         //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
         int allowance = (int)(allowanceFactor * overallEstModuleSize);
         int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance);
         int alignmentAreaRightX = Math.Min(image.Width - 1, estAlignmentX + allowance);
         if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3)
         {
            return null;
         }

         int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance);
         int alignmentAreaBottomY = Math.Min(image.Height - 1, estAlignmentY + allowance);

         var alignmentFinder = new AlignmentPatternFinder(
            image,
            alignmentAreaLeftX,
            alignmentAreaTopY,
            alignmentAreaRightX - alignmentAreaLeftX,
            alignmentAreaBottomY - alignmentAreaTopY,
            overallEstModuleSize,
            resultPointCallback);

         return alignmentFinder.find();
      }
   }
}

 

qrcode->detector目录下的FinderPatternFinder类:

技术分享
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Collections.Generic;

using ZXing.Common;

namespace ZXing.QrCode.Internal
{
   /// <summary>
   /// <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
   /// markers at three corners of a QR Code.</p>
   /// 
   /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
   /// </summary>
   /// <author>Sean Owen</author>
   public class FinderPatternFinder
   {
      private const int CENTER_QUORUM = 2;
      /// <summary>
      /// 1 pixel/module times 3 modules/center
      /// </summary>
      protected internal const int MIN_SKIP = 3; 
      /// <summary>
      /// support up to version 10 for mobile clients
      /// </summary>
      protected internal const int MAX_MODULES = 57;
      private const int INTEGER_MATH_SHIFT = 8;

      private readonly BitMatrix image;
      private List<FinderPattern> possibleCenters; // Records the alignment patterns cordination information
      private bool hasSkipped;
      private readonly int[] crossCheckStateCount;
      private readonly ResultPointCallback resultPointCallback;

      /// <summary>
      /// <p>Creates a finder that will search the image for three finder patterns.</p>
      /// </summary>
      /// <param name="image">image to search</param>
      public FinderPatternFinder(BitMatrix image)
         : this(image, null)
      {
      }

      /// <summary>
      /// Initializes a new instance of the <see cref="FinderPatternFinder"/> class.
      /// </summary>
      /// <param name="image">The image.</param>
      /// <param name="resultPointCallback">The result point callback.</param>
      public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback)
      {
         this.image = image;
         this.possibleCenters = new List<FinderPattern>();
         this.crossCheckStateCount = new int[5];
         this.resultPointCallback = resultPointCallback;
      }

      /// <summary>
      /// Gets the image.
      /// </summary>
      virtual protected internal BitMatrix Image
      {
         get
         {
            return image;
         }
      }

      /// <summary>
      /// Gets the possible centers.
      /// </summary>
      virtual protected internal List<FinderPattern> PossibleCenters
      {
         get
         {
            return possibleCenters;
         }
      }

      internal virtual FinderPatternInfo find(IDictionary<DecodeHintType, object> hints)
      {
         bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
         bool pureBarcode = hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE);
         int maxI = image.Height;
         int maxJ = image.Width;
         // We are looking for black/white/black/white/black modules in
         // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far

         // Let‘s assume that the maximum version QR Code we support takes up 1/4 the height of the
         // image, and then account for the center being 3 modules in size. This gives the smallest
         // number of pixels the center could be, so skip this often. When trying harder, look for all
         // QR versions regardless of how dense they are.
         int iSkip = (3 * maxI) / (4 * MAX_MODULES);
         if (iSkip < MIN_SKIP || tryHarder)
         {
            iSkip = MIN_SKIP;
         }

         bool done = false;
         int[] stateCount = new int[5];
         for (int i = iSkip - 1; i < maxI && !done; i += iSkip)
         {
            // Get a row of black/white values
            stateCount[0] = 0;
            stateCount[1] = 0;
            stateCount[2] = 0;
            stateCount[3] = 0;
            stateCount[4] = 0;
            int currentState = 0;
            for (int j = 0; j < maxJ; j++)
            {
               if (image[j, i])
               {
                  // Black pixel
                  if ((currentState & 1) == 1)
                  {
                     // Counting white pixels
                     currentState++;
                  }
                  stateCount[currentState]++;
               }
               else
               {
                  // White pixel
                  if ((currentState & 1) == 0)
                  {
                     // Counting black pixels
                     if (currentState == 4)
                     {
                        // A winner?
                        if (foundPatternCross(stateCount))
                        {
                           // Yes(possible alignment pattern was found)
                           bool confirmed = handlePossibleCenter(stateCount, i, j, pureBarcode); // Check whether the alignment pattern is true or fake
                           if (confirmed)
                           {
                              // Start examining every other line. Checking each line turned out to be too
                              // expensive and didn‘t improve performance.
                              iSkip = 2;
                              if (hasSkipped) // If at least two alignment patterns were found and the skip parameter has been calculated
                              {
                                 done = haveMultiplyConfirmedCenters(); // Check whether we have found at least 3 finder patterns
                              }
                              else
                              {
                                 int rowSkip = findRowSkip(); // Calculate number of rows we could safely skip during scanning, based on the first two finder patterns
                                 if (rowSkip > stateCount[2])
                                 {
                                    // Skip rows between row of lower confirmed center and top of presumed third confirmed center
                                    // but back up a bit to get a full chance of detecting it, entire width of center of finder pattern

                                    // Skip by rowSkip, but back off by stateCount[2] (size of last center of pattern we saw) 
                                    // to be conservative, and also back off by iSkip which is about to be re-added
                                    i += rowSkip - stateCount[2] - iSkip;
                                    j = maxJ - 1;
                                 }
                              }
                           }
                           else
                           {
                              stateCount[0] = stateCount[2];
                              stateCount[1] = stateCount[3];
                              stateCount[2] = stateCount[4];
                              stateCount[3] = 1;
                              stateCount[4] = 0;
                              currentState = 3;
                              continue;
                           }
                           // Clear state to start looking again
                           currentState = 0;
                           stateCount[0] = 0;
                           stateCount[1] = 0;
                           stateCount[2] = 0;
                           stateCount[3] = 0;
                           stateCount[4] = 0;
                        }
                        else
                        {
                           // No, shift counts back by two
                           stateCount[0] = stateCount[2];
                           stateCount[1] = stateCount[3];
                           stateCount[2] = stateCount[4];
                           stateCount[3] = 1;
                           stateCount[4] = 0;
                           currentState = 3;
                        }
                     }
                     else
                     {
                        stateCount[++currentState]++;
                     }
                  }
                  else
                  {
                     // Counting white pixels
                     stateCount[currentState]++;
                  }
               }
            }
            if (foundPatternCross(stateCount))
            {
               bool confirmed = handlePossibleCenter(stateCount, i, maxJ, pureBarcode);
               if (confirmed)
               {
                  iSkip = stateCount[0];
                  if (hasSkipped)
                  {
                     // Found a third one
                     done = haveMultiplyConfirmedCenters();
                  }
               }
            }
         }

         FinderPattern[] patternInfo = selectBestPatterns();
         if (patternInfo == null)
            return null;

         ResultPoint.orderBestPatterns(patternInfo);

         return new FinderPatternInfo(patternInfo);
      }

      /// <summary> Given a count of black/white/black/white/black pixels just seen and an end position,
      /// figures the location of the center of this run.
      /// </summary>
      private static float? centerFromEnd(int[] stateCount, int end)
      {
         var result = (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
         if (Single.IsNaN(result))
            return null;
         return result;
      }

      /// <param name="stateCount">count of black/white/black/white/black pixels just read
      /// </param>
      /// <returns> true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
      /// used by finder patterns to be considered a match
      /// </returns>
      protected internal static bool foundPatternCross(int[] stateCount)
      {
         int totalModuleSize = 0;
         for (int i = 0; i < 5; i++)
         {
            int count = stateCount[i];
            if (count == 0)
            {
               return false;
            }
            totalModuleSize += count;
         }
         if (totalModuleSize < 7)
         {
            return false;
         }
         int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; // 1+1+3+1+1=7, at least 7 modules
         int maxVariance = moduleSize / 2;
         // Allow less than 50% variance from 1-1-3-1-1 proportions
         return Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&
             Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&
             Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&
             Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&
             Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
      }

      private int[] CrossCheckStateCount
      {
         get
         {
            crossCheckStateCount[0] = 0;
            crossCheckStateCount[1] = 0;
            crossCheckStateCount[2] = 0;
            crossCheckStateCount[3] = 0;
            crossCheckStateCount[4] = 0;
            return crossCheckStateCount;
         }
      }

      /// <summary>
      /// After a vertical and horizontal scan finds a potential finder pattern, this method
      /// "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
      /// finder pattern to see if the same proportion is detected.
      /// </summary>
      /// <param name="startI">row where a finder pattern was detected</param>
      /// <param name="centerJ">center of the section that appears to cross a finder pattern</param>
      /// <param name="maxCount">maximum reasonable number of modules that should be observed in any reading state, based on the results of the horizontal scan</param>
      /// <param name="originalStateCountTotal">The original state count total.</param>
      /// <returns>true if proportions are withing expected limits</returns>
      private bool crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal)
      {
         int maxI = image.Height;
         int maxJ = image.Width;
         int[] stateCount = CrossCheckStateCount;

         // Start counting up, left from center finding black center mass
         int i = 0;
         while (startI - i >= 0 && image[centerJ - i, startI - i])
         {
            stateCount[2]++;
            i++;
         }

         if ((startI - i < 0) || (centerJ - i < 0))
         {
            return false;
         }

         // Continue up, left finding white space
         while ((startI - i >= 0) && (centerJ - i >= 0) && !image[centerJ - i, startI - i] && stateCount[1] <= maxCount)
         {
            stateCount[1]++;
            i++;
         }

         // If already too many modules in this state or ran off the edge:
         if ((startI - i < 0) || (centerJ - i < 0) || stateCount[1] > maxCount)
         {
            return false;
         }

         // Continue up, left finding black border
         while ((startI - i >= 0) && (centerJ - i >= 0) && image[centerJ - i, startI - i] && stateCount[0] <= maxCount)
         {
            stateCount[0]++;
            i++;
         }
         if (stateCount[0] > maxCount)
         {
            return false;
         }

         // Now also count down, right from center
         i = 1;
         while ((startI + i < maxI) && (centerJ + i < maxJ) && image[centerJ + i, startI + i])
         {
            stateCount[2]++;
            i++;
         }

         // Ran off the edge?
         if ((startI + i >= maxI) || (centerJ + i >= maxJ))
         {
            return false;
         }

         while ((startI + i < maxI) && (centerJ + i < maxJ) && !image[centerJ + i, startI + i] && stateCount[3] < maxCount)
         {
            stateCount[3]++;
            i++;
         }

         if ((startI + i >= maxI) || (centerJ + i >= maxJ) || stateCount[3] >= maxCount)
         {
            return false;
         }

         while ((startI + i < maxI) && (centerJ + i < maxJ) && image[centerJ + i, startI + i] && stateCount[4] < maxCount)
         {
            stateCount[4]++;
            i++;
         }

         if (stateCount[4] >= maxCount)
         {
            return false;
         }

         // If we found a finder-pattern-like section, but its size is more than 100% different than
         // the original, assume it‘s a false positive
         int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
         return Math.Abs(stateCountTotal - originalStateCountTotal) < 2*originalStateCountTotal &&
                foundPatternCross(stateCount);
      }

      /// <summary>
      ///   <p>After a horizontal scan finds a potential finder pattern, this method
      /// "cross-checks" by scanning down vertically through the center of the possible
      /// finder pattern to see if the same proportion is detected.</p>
      /// </summary>
      /// <param name="startI">row where a finder pattern was detected</param>
      /// <param name="centerJ">center of the section that appears to cross a finder pattern</param>
      /// <param name="maxCount">maximum reasonable number of modules that should be
      /// observed in any reading state, based on the results of the horizontal scan</param>
      /// <param name="originalStateCountTotal">The original state count total.</param>
      /// <returns>
      /// vertical center of finder pattern, or null if not found
      /// </returns>
      private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
      {
         int maxI = image.Height;
         int[] stateCount = CrossCheckStateCount;

         // Start counting up from center
         int i = startI;
         while (i >= 0 && image[centerJ, i])
         {
            stateCount[2]++;
            i--;
         }
         if (i < 0)
         {
            return null;
         }
         while (i >= 0 && !image[centerJ, i] && stateCount[1] <= maxCount)
         {
            stateCount[1]++;
            i--;
         }
         // If already too many modules in this state or ran off the edge:
         if (i < 0 || stateCount[1] > maxCount)
         {
            return null;
         }
         while (i >= 0 && image[centerJ, i] && stateCount[0] <= maxCount)
         {
            stateCount[0]++;
            i--;
         }
         if (stateCount[0] > maxCount)
         {
            return null;
         }

         // Now also count down from center
         i = startI + 1;
         while (i < maxI && image[centerJ, i])
         {
            stateCount[2]++;
            i++;
         }
         if (i == maxI)
         {
            return null;
         }
         while (i < maxI && !image[centerJ, i] && stateCount[3] < maxCount)
         {
            stateCount[3]++;
            i++;
         }
         if (i == maxI || stateCount[3] >= maxCount)
         {
            return null;
         }
         while (i < maxI && image[centerJ, i] && stateCount[4] < maxCount)
         {
            stateCount[4]++;
            i++;
         }
         if (stateCount[4] >= maxCount)
         {
            return null;
         }

         // If we found a finder-pattern-like section, but its size is more than 40% different than
         // the original, assume it‘s a false positive
         int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
         if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
         {
            return null;
         }

         return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null;
      }

      /// <summary> <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
      /// except it reads horizontally instead of vertically. This is used to cross-cross
      /// check a vertical cross check and locate the real center of the alignment pattern.</p>
      /// </summary>
      private float? crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal)
      {
         int maxJ = image.Width;
         int[] stateCount = CrossCheckStateCount;

         int j = startJ;
         while (j >= 0 && image[j, centerI])
         {
            stateCount[2]++;
            j--;
         }
         if (j < 0)
         {
            return null;
         }
         while (j >= 0 && !image[j, centerI] && stateCount[1] <= maxCount)
         {
            stateCount[1]++;
            j--;
         }
         if (j < 0 || stateCount[1] > maxCount)
         {
            return null;
         }
         while (j >= 0 && image[j, centerI] && stateCount[0] <= maxCount)
         {
            stateCount[0]++;
            j--;
         }
         if (stateCount[0] > maxCount)
         {
            return null;
         }

         j = startJ + 1;
         while (j < maxJ && image[j, centerI])
         {
            stateCount[2]++;
            j++;
         }
         if (j == maxJ)
         {
            return null;
         }
         while (j < maxJ && !image[j, centerI] && stateCount[3] < maxCount)
         {
            stateCount[3]++;
            j++;
         }
         if (j == maxJ || stateCount[3] >= maxCount)
         {
            return null;
         }
         while (j < maxJ && image[j, centerI] && stateCount[4] < maxCount)
         {
            stateCount[4]++;
            j++;
         }
         if (stateCount[4] >= maxCount)
         {
            return null;
         }

         // If we found a finder-pattern-like section, but its size is significantly different than
         // the original, assume it‘s a false positive
         int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
         if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
         {
            return null;
         }

         return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : null;
      }

      /// <summary>
      ///   <p>This is called when a horizontal scan finds a possible alignment pattern. It will
      /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check
      /// with another horizontal scan. This is needed primarily to locate the real horizontal
      /// center of the pattern in cases of extreme skew.
      /// And then we cross-cross-cross check with another diagonal scan.</p>
      /// If that succeeds the finder pattern location is added to a list that tracks
      /// the number of times each location has been nearly-matched as a finder pattern.
      /// Each additional find is more evidence that the location is in fact a finder
      /// pattern center
      /// </summary>
      /// <param name="stateCount">reading state module counts from horizontal scan</param>
      /// <param name="i">row where finder pattern may be found</param>
      /// <param name="j">end of possible finder pattern in row</param>
      /// <param name="pureBarcode">if set to <c>true</c> [pure barcode].</param>
      /// <returns>
      /// true if a finder pattern candidate was found this time
      /// </returns>
      protected bool handlePossibleCenter(int[] stateCount, int i, int j, bool pureBarcode)
      {
         int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
         float? centerJ = centerFromEnd(stateCount, j);
         if (centerJ == null)
            return false;
         float? centerI = crossCheckVertical(i, (int)centerJ.Value, stateCount[2], stateCountTotal); // Cross Check Vertical
            if (centerI != null)
         {
            // Re-cross check
            centerJ = crossCheckHorizontal((int)centerJ.Value, (int)centerI.Value, stateCount[2], stateCountTotal); // Cross Check Horizontal
                if (centerJ != null &&
               (!pureBarcode || crossCheckDiagonal((int) centerI, (int) centerJ, stateCount[2], stateCountTotal))) // Cross Check Diagonal
                {
               float estimatedModuleSize = stateCountTotal / 7.0f;
               bool found = false;
               for (int index = 0; index < possibleCenters.Count; index++)
               {
                  var center = possibleCenters[index];
                  // Look for about the same center and module size:
                  if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value))
                  {
                     possibleCenters.RemoveAt(index);
                     possibleCenters.Insert(index, center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize));

                     found = true;
                     break;
                  }
               }
               if (!found)
               {
                  var point = new FinderPattern(centerJ.Value, centerI.Value, estimatedModuleSize);

                  possibleCenters.Add(point);
                  if (resultPointCallback != null)
                  {

                     resultPointCallback(point);
                  }
               }
               return true;
            }
         }
         return false;
      }

      /// <returns> number of rows we could safely skip during scanning, based on the first
      /// two finder patterns that have been located. In some cases their position will
      /// allow us to infer that the third pattern must lie below a certain point farther
      /// down in the image.
      /// </returns>
      private int findRowSkip()
      {
         int max = possibleCenters.Count;
         if (max <= 1)
         {
            return 0;
         }
         ResultPoint firstConfirmedCenter = null;
         foreach (var center in possibleCenters)
         {
            if (center.Count >= CENTER_QUORUM)
            {
               if (firstConfirmedCenter == null)
               {
                  firstConfirmedCenter = center;
               }
               else
               {
                  // We have two confirmed centers
                  // How far down can we skip before resuming looking for the next
                  // pattern? In the worst case, only the difference between the
                  // difference in the x / y coordinates of the two centers.
                  // This is the case where you find top left last.
                  hasSkipped = true;
                  //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index=‘!DefaultContextWindowIndex‘&keyword=‘jlca1042‘"
                  return (int)(Math.Abs(firstConfirmedCenter.X - center.X) - Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2;
               }
            }
         }
         return 0;
      }

      /// <returns> true if we have found at least 3 finder patterns that have been detected
      /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
      /// candidates is "pretty similar"
      /// </returns>
      private bool haveMultiplyConfirmedCenters()
      {
         int confirmedCount = 0;
         float totalModuleSize = 0.0f;
         int max = possibleCenters.Count;
         foreach (var pattern in possibleCenters)
         {
            if (pattern.Count >= CENTER_QUORUM)
            {
               confirmedCount++;
               totalModuleSize += pattern.EstimatedModuleSize;
            }
         }
         if (confirmedCount < 3)
         {
            return false;
         }
         // OK, we have at least 3 confirmed centers, but, it‘s possible that one is a "false positive"
         // and that we need to keep looking. We detect this by asking if the estimated module sizes
         // vary too much. We arbitrarily say that when the total deviation from average exceeds
         // 5% of the total module size estimates, it‘s too much.
         float average = totalModuleSize / max;
         float totalDeviation = 0.0f;
         for (int i = 0; i < max; i++)
         {
            var pattern = possibleCenters[i];
            totalDeviation += Math.Abs(pattern.EstimatedModuleSize - average);
         }
         return totalDeviation <= 0.05f * totalModuleSize;
      }

      /// <returns> the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
      /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
      /// size differs from the average among those patterns the least
      /// </returns>
      private FinderPattern[] selectBestPatterns()
      {
         int startSize = possibleCenters.Count;
         if (startSize < 3)
         {
            // Couldn‘t find enough finder patterns
            return null;
         }

         // Filter outlier possibilities whose module size is too different
         if (startSize > 3)
         {
            // But we can only afford to do so if we have at least 4 possibilities to choose from
            float totalModuleSize = 0.0f;
            float square = 0.0f;
            foreach (var center in possibleCenters)
            {
               float size = center.EstimatedModuleSize;
               totalModuleSize += size;
               square += size * size;
            }
            float average = totalModuleSize / startSize;
            float stdDev = (float)Math.Sqrt(square / startSize - average * average);

            possibleCenters.Sort(new FurthestFromAverageComparator(average));

            float limit = Math.Max(0.2f * average, stdDev);

            for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++)
            {
               FinderPattern pattern = possibleCenters[i];
               if (Math.Abs(pattern.EstimatedModuleSize - average) > limit)
               {
                  possibleCenters.RemoveAt(i);
                  i--;
               }
            }
         }

         if (possibleCenters.Count > 3)
         {
            // Throw away all but those first size candidate points we found.

            float totalModuleSize = 0.0f;
            foreach (var possibleCenter in possibleCenters)
            {
               totalModuleSize += possibleCenter.EstimatedModuleSize;
            }

            float average = totalModuleSize / possibleCenters.Count;

            possibleCenters.Sort(new CenterComparator(average));

            //possibleCenters.subList(3, possibleCenters.Count).clear();
            possibleCenters = possibleCenters.GetRange(0, 3);
         }

         return new[]
                   {
                      possibleCenters[0],
                      possibleCenters[1],
                      possibleCenters[2]
                   };
      }

      /// <summary>
      /// Orders by furthest from average
      /// </summary>
      private sealed class FurthestFromAverageComparator : IComparer<FinderPattern>
      {
         private readonly float average;

         public FurthestFromAverageComparator(float f)
         {
            average = f;
         }

         public int Compare(FinderPattern x, FinderPattern y)
         {
            float dA = Math.Abs(y.EstimatedModuleSize - average);
            float dB = Math.Abs(x.EstimatedModuleSize - average);
            return dA < dB ? -1 : dA == dB ? 0 : 1;
         }
      }

      /// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary>
      private sealed class CenterComparator : IComparer<FinderPattern>
      {
         private readonly float average;

         public CenterComparator(float f)
         {
            average = f;
         }

         public int Compare(FinderPattern x, FinderPattern y)
         {
            if (y.Count == x.Count)
            {
               float dA = Math.Abs(y.EstimatedModuleSize - average);
               float dB = Math.Abs(x.EstimatedModuleSize - average);
               return dA < dB ? 1 : dA == dB ? 0 : -1;
            }
            return y.Count - x.Count;
         }
      }
   }
}
View Code

寻找PatternFinder流程为:先按照1:1:3:1:1的比例逐行扫描,寻找Qrcode的定位点并校验点位点(横向,竖向,对角线斜向),找到最初两个定位点以后,

通过findRowSkip()更新隔行检测参数提高检测效率,继续寻找定位点直至定位点全部找到,然后通过selectBestPatterns()选择最优的定位点,然后将最优

定位点相关信息处理后返回供上层调用。

 

qrcode->decoder目录下的Decoder(密封)类:

 

2.源码架构

BarcodeReader类继承了BarcodeReaderGeneric类,实现了接口IBarcodeReader, IMultipleBarcodeReader:

public class BarcodeReader : BarcodeReaderGeneric<Bitmap>, IBarcodeReader, IMultipleBarcodeReader

BarcodeReaderGeneric类实现了接口IBarcodeReaderGeneric<T>, IMultipleBarcodeReaderGeneric<T>。其中Decode虚拟方法为:

      /// <summary>
      /// Tries to decode a barcode within an image which is given by a luminance source.
      /// That method gives a chance to prepare a luminance source completely before calling
      /// the time consuming decoding method. On the other hand there is a chance to create
      /// a luminance source which is independent from external resources (like Bitmap objects)
      /// and the decoding call can be made in a background thread.
      /// </summary>
      /// <param name="luminanceSource">The luminance source.</param>
      /// <returns></returns>
      virtual public Result Decode(LuminanceSource luminanceSource)
      {
         var result = default(Result);
         var binarizer = CreateBinarizer(luminanceSource);
         var binaryBitmap = new BinaryBitmap(binarizer);
         var multiformatReader = Reader as MultiFormatReader;
         var rotationCount = 0;
         var rotationMaxCount = 1;

         if (AutoRotate)
         {
            Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
            rotationMaxCount = 4;
         }
         else
         {
            if (Options.Hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION))
               Options.Hints.Remove(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
         }

         for (; rotationCount < rotationMaxCount; rotationCount++)
         {
            if (usePreviousState && multiformatReader != null)
            {
               result = multiformatReader.decodeWithState(binaryBitmap);
            }
            else
            {
               result = Reader.decode(binaryBitmap, Options.Hints);
               usePreviousState = true;
            }

            if (result == null)
            {
               if (TryInverted && luminanceSource.InversionSupported)
               {
                  binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                  if (usePreviousState && multiformatReader != null)
                  {
                     result = multiformatReader.decodeWithState(binaryBitmap);
                  }
                  else
                  {
                     result = Reader.decode(binaryBitmap, Options.Hints);
                     usePreviousState = true;
                  }
               }
            }

            if (result != null ||
                !luminanceSource.RotateSupported ||
                !AutoRotate)
               break;

            binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
         }

         if (result != null)
         {
            if (result.ResultMetadata == null)
            {
               result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
            }
            else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
            {
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
            }
            else
            {
               // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
            }

            OnResultFound(result);
         }

         return result;
      }

 

2.编码(待续)

【开源】ZXING的.NET版本源码解析

标签:hid   continue   should   .dll   tom   power   info   corners   esb   

原文地址:http://www.cnblogs.com/jayhust/p/5890156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!