PageRenderTime 114ms CodeModel.GetById 29ms RepoModel.GetById 2ms app.codeStats 0ms

/silverlight/qrcode/detector/AlignmentPatternFinder.cs

https://bitbucket.org/jrasanen/silverlightzxing
C# | 339 lines | 203 code | 15 blank | 121 comment | 47 complexity | c90fb8a8461d96f5198cbeff70c6c48f MD5 | raw file
  1. /*
  2. * Copyright 2007 ZXing authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. using System;
  17. using ReaderException = com.google.zxing.ReaderException;
  18. using ResultPoint = com.google.zxing.ResultPoint;
  19. using ResultPointCallback = com.google.zxing.ResultPointCallback;
  20. using BitMatrix = com.google.zxing.common.BitMatrix;
  21. namespace com.google.zxing.qrcode.detector
  22. {
  23. /// <summary> <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
  24. /// patterns but are smaller and appear at regular intervals throughout the image.</p>
  25. ///
  26. /// <p>At the moment this only looks for the bottom-right alignment pattern.</p>
  27. ///
  28. /// <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
  29. /// pasted and stripped down here for maximum performance but does unfortunately duplicate
  30. /// some code.</p>
  31. ///
  32. /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
  33. ///
  34. /// </summary>
  35. /// <author> Sean Owen
  36. /// </author>
  37. /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
  38. /// </author>
  39. sealed class AlignmentPatternFinder
  40. {
  41. //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  42. private BitMatrix image;
  43. //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  44. private System.Collections.Generic.List<Object> possibleCenters;
  45. //UPGRADE_NOTE: Final was removed from the declaration of 'startX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  46. private int startX;
  47. //UPGRADE_NOTE: Final was removed from the declaration of 'startY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  48. private int startY;
  49. //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  50. private int width;
  51. //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  52. private int height;
  53. //UPGRADE_NOTE: Final was removed from the declaration of 'moduleSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  54. private float moduleSize;
  55. //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  56. private int[] crossCheckStateCount;
  57. //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  58. private ResultPointCallback resultPointCallback;
  59. /// <summary> <p>Creates a finder that will look in a portion of the whole image.</p>
  60. ///
  61. /// </summary>
  62. /// <param name="image">image to search
  63. /// </param>
  64. /// <param name="startX">left column from which to start searching
  65. /// </param>
  66. /// <param name="startY">top row from which to start searching
  67. /// </param>
  68. /// <param name="width">width of region to search
  69. /// </param>
  70. /// <param name="height">height of region to search
  71. /// </param>
  72. /// <param name="moduleSize">estimated module size so far
  73. /// </param>
  74. internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback)
  75. {
  76. this.image = image;
  77. this.possibleCenters = new System.Collections.Generic.List<Object>(5);
  78. this.startX = startX;
  79. this.startY = startY;
  80. this.width = width;
  81. this.height = height;
  82. this.moduleSize = moduleSize;
  83. this.crossCheckStateCount = new int[3];
  84. this.resultPointCallback = resultPointCallback;
  85. }
  86. /// <summary> <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
  87. /// it's pretty performance-critical and so is written to be fast foremost.</p>
  88. ///
  89. /// </summary>
  90. /// <returns> {@link AlignmentPattern} if found
  91. /// </returns>
  92. /// <throws> ReaderException if not found </throws>
  93. internal AlignmentPattern find()
  94. {
  95. int startX = this.startX;
  96. int height = this.height;
  97. int maxJ = startX + width;
  98. int middleI = startY + (height >> 1);
  99. // We are looking for black/white/black modules in 1:1:1 ratio;
  100. // this tracks the number of black/white/black modules seen so far
  101. int[] stateCount = new int[3];
  102. for (int iGen = 0; iGen < height; iGen++)
  103. {
  104. // Search from middle outwards
  105. int i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1));
  106. stateCount[0] = 0;
  107. stateCount[1] = 0;
  108. stateCount[2] = 0;
  109. int j = startX;
  110. // Burn off leading white pixels before anything else; if we start in the middle of
  111. // a white run, it doesn't make sense to count its length, since we don't know if the
  112. // white run continued to the left of the start point
  113. while (j < maxJ && !image.get_Renamed(j, i))
  114. {
  115. j++;
  116. }
  117. int currentState = 0;
  118. while (j < maxJ)
  119. {
  120. if (image.get_Renamed(j, i))
  121. {
  122. // Black pixel
  123. if (currentState == 1)
  124. {
  125. // Counting black pixels
  126. stateCount[currentState]++;
  127. }
  128. else
  129. {
  130. // Counting white pixels
  131. if (currentState == 2)
  132. {
  133. // A winner?
  134. if (foundPatternCross(stateCount))
  135. {
  136. // Yes
  137. AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);
  138. if (confirmed != null)
  139. {
  140. return confirmed;
  141. }
  142. }
  143. stateCount[0] = stateCount[2];
  144. stateCount[1] = 1;
  145. stateCount[2] = 0;
  146. currentState = 1;
  147. }
  148. else
  149. {
  150. stateCount[++currentState]++;
  151. }
  152. }
  153. }
  154. else
  155. {
  156. // White pixel
  157. if (currentState == 1)
  158. {
  159. // Counting black pixels
  160. currentState++;
  161. }
  162. stateCount[currentState]++;
  163. }
  164. j++;
  165. }
  166. if (foundPatternCross(stateCount))
  167. {
  168. AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);
  169. if (confirmed != null)
  170. {
  171. return confirmed;
  172. }
  173. }
  174. }
  175. // Hmm, nothing we saw was observed and confirmed twice. If we had
  176. // any guess at all, return it.
  177. if (!(possibleCenters.Count == 0))
  178. {
  179. return (AlignmentPattern) possibleCenters[0];
  180. }
  181. throw ReaderException.Instance;
  182. }
  183. /// <summary> Given a count of black/white/black pixels just seen and an end position,
  184. /// figures the location of the center of this black/white/black run.
  185. /// </summary>
  186. private static float centerFromEnd(int[] stateCount, int end)
  187. {
  188. //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'"
  189. return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;
  190. }
  191. /// <param name="stateCount">count of black/white/black pixels just read
  192. /// </param>
  193. /// <returns> true iff the proportions of the counts is close enough to the 1/1/1 ratios
  194. /// used by alignment patterns to be considered a match
  195. /// </returns>
  196. private bool foundPatternCross(int[] stateCount)
  197. {
  198. float moduleSize = this.moduleSize;
  199. float maxVariance = moduleSize / 2.0f;
  200. for (int i = 0; i < 3; i++)
  201. {
  202. if (System.Math.Abs(moduleSize - stateCount[i]) >= maxVariance)
  203. {
  204. return false;
  205. }
  206. }
  207. return true;
  208. }
  209. /// <summary> <p>After a horizontal scan finds a potential alignment pattern, this method
  210. /// "cross-checks" by scanning down vertically through the center of the possible
  211. /// alignment pattern to see if the same proportion is detected.</p>
  212. ///
  213. /// </summary>
  214. /// <param name="startI">row where an alignment pattern was detected
  215. /// </param>
  216. /// <param name="centerJ">center of the section that appears to cross an alignment pattern
  217. /// </param>
  218. /// <param name="maxCount">maximum reasonable number of modules that should be
  219. /// observed in any reading state, based on the results of the horizontal scan
  220. /// </param>
  221. /// <returns> vertical center of alignment pattern, or {@link Float#NaN} if not found
  222. /// </returns>
  223. private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
  224. {
  225. BitMatrix image = this.image;
  226. int maxI = image.Height;
  227. int[] stateCount = crossCheckStateCount;
  228. stateCount[0] = 0;
  229. stateCount[1] = 0;
  230. stateCount[2] = 0;
  231. // Start counting up from center
  232. int i = startI;
  233. while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
  234. {
  235. stateCount[1]++;
  236. i--;
  237. }
  238. // If already too many modules in this state or ran off the edge:
  239. if (i < 0 || stateCount[1] > maxCount)
  240. {
  241. return System.Single.NaN;
  242. }
  243. while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
  244. {
  245. stateCount[0]++;
  246. i--;
  247. }
  248. if (stateCount[0] > maxCount)
  249. {
  250. return System.Single.NaN;
  251. }
  252. // Now also count down from center
  253. i = startI + 1;
  254. while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
  255. {
  256. stateCount[1]++;
  257. i++;
  258. }
  259. if (i == maxI || stateCount[1] > maxCount)
  260. {
  261. return System.Single.NaN;
  262. }
  263. while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[2] <= maxCount)
  264. {
  265. stateCount[2]++;
  266. i++;
  267. }
  268. if (stateCount[2] > maxCount)
  269. {
  270. return System.Single.NaN;
  271. }
  272. int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
  273. if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
  274. {
  275. return System.Single.NaN;
  276. }
  277. return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
  278. }
  279. /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  280. /// cross check with a vertical scan, and if successful, will see if this pattern had been
  281. /// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
  282. /// found the alignment pattern.</p>
  283. ///
  284. /// </summary>
  285. /// <param name="stateCount">reading state module counts from horizontal scan
  286. /// </param>
  287. /// <param name="i">row where alignment pattern may be found
  288. /// </param>
  289. /// <param name="j">end of possible alignment pattern in row
  290. /// </param>
  291. /// <returns> {@link AlignmentPattern} if we have found the same pattern twice, or null if not
  292. /// </returns>
  293. private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j)
  294. {
  295. int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
  296. float centerJ = centerFromEnd(stateCount, j);
  297. //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'"
  298. float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal);
  299. if (!System.Single.IsNaN(centerI))
  300. {
  301. //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'"
  302. float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;
  303. int max = possibleCenters.Count;
  304. for (int index = 0; index < max; index++)
  305. {
  306. AlignmentPattern center = (AlignmentPattern) possibleCenters[index];
  307. // Look for about the same center and module size:
  308. if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
  309. {
  310. return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
  311. }
  312. }
  313. // Hadn't found this before; save it
  314. ResultPoint point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
  315. possibleCenters.Add(point);
  316. if (resultPointCallback != null)
  317. {
  318. resultPointCallback.foundPossibleResultPoint(point);
  319. }
  320. }
  321. return null;
  322. }
  323. }
  324. }