PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/silverlight/qrcode/detector/FinderPatternFinder.cs

https://bitbucket.org/jrasanen/silverlightzxing
C# | 646 lines | 458 code | 37 blank | 151 comment | 108 complexity | eab5a418d5d2e840c748746b12d7b139 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 DecodeHintType = com.google.zxing.DecodeHintType;
  18. using ReaderException = com.google.zxing.ReaderException;
  19. using ResultPoint = com.google.zxing.ResultPoint;
  20. using ResultPointCallback = com.google.zxing.ResultPointCallback;
  21. using Collections = com.google.zxing.common.Collections;
  22. using Comparator = com.google.zxing.common.Comparator;
  23. using BitMatrix = com.google.zxing.common.BitMatrix;
  24. namespace com.google.zxing.qrcode.detector
  25. {
  26. /// <summary> <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
  27. /// markers at three corners of a QR Code.</p>
  28. ///
  29. /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
  30. ///
  31. /// </summary>
  32. /// <author> Sean Owen
  33. /// </author>
  34. /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
  35. /// </author>
  36. public class FinderPatternFinder
  37. {
  38. virtual protected internal BitMatrix Image
  39. {
  40. get
  41. {
  42. return image;
  43. }
  44. }
  45. virtual protected internal System.Collections.Generic.List<Object> PossibleCenters
  46. {
  47. get
  48. {
  49. return possibleCenters;
  50. }
  51. }
  52. private int[] CrossCheckStateCount
  53. {
  54. get
  55. {
  56. crossCheckStateCount[0] = 0;
  57. crossCheckStateCount[1] = 0;
  58. crossCheckStateCount[2] = 0;
  59. crossCheckStateCount[3] = 0;
  60. crossCheckStateCount[4] = 0;
  61. return crossCheckStateCount;
  62. }
  63. }
  64. private const int CENTER_QUORUM = 2;
  65. protected internal const int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
  66. protected internal const int MAX_MODULES = 57; // support up to version 10 for mobile clients
  67. private const int INTEGER_MATH_SHIFT = 8;
  68. //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  69. private BitMatrix image;
  70. //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  71. private System.Collections.Generic.List<Object> possibleCenters;
  72. private bool hasSkipped;
  73. //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  74. private int[] crossCheckStateCount;
  75. //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
  76. private ResultPointCallback resultPointCallback;
  77. /// <summary> <p>Creates a finder that will search the image for three finder patterns.</p>
  78. ///
  79. /// </summary>
  80. /// <param name="image">image to search
  81. /// </param>
  82. public FinderPatternFinder(BitMatrix image):this(image, null)
  83. {
  84. }
  85. public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback)
  86. {
  87. this.image = image;
  88. this.possibleCenters = new System.Collections.Generic.List<Object>(10);
  89. this.crossCheckStateCount = new int[5];
  90. this.resultPointCallback = resultPointCallback;
  91. }
  92. internal virtual FinderPatternInfo find(System.Collections.Generic.Dictionary<Object,Object> hints)
  93. {
  94. bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
  95. int maxI = image.Height;
  96. int maxJ = image.Width;
  97. // We are looking for black/white/black/white/black modules in
  98. // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
  99. // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  100. // image, and then account for the center being 3 modules in size. This gives the smallest
  101. // number of pixels the center could be, so skip this often. When trying harder, look for all
  102. // QR versions regardless of how dense they are.
  103. int iSkip = (3 * maxI) / (4 * MAX_MODULES);
  104. if (iSkip < MIN_SKIP || tryHarder)
  105. {
  106. iSkip = MIN_SKIP;
  107. }
  108. bool done = false;
  109. int[] stateCount = new int[5];
  110. for (int i = iSkip - 1; i < maxI && !done; i += iSkip)
  111. {
  112. // Get a row of black/white values
  113. stateCount[0] = 0;
  114. stateCount[1] = 0;
  115. stateCount[2] = 0;
  116. stateCount[3] = 0;
  117. stateCount[4] = 0;
  118. int currentState = 0;
  119. for (int j = 0; j < maxJ; j++)
  120. {
  121. if (image.get_Renamed(j, i))
  122. {
  123. // Black pixel
  124. if ((currentState & 1) == 1)
  125. {
  126. // Counting white pixels
  127. currentState++;
  128. }
  129. stateCount[currentState]++;
  130. }
  131. else
  132. {
  133. // White pixel
  134. if ((currentState & 1) == 0)
  135. {
  136. // Counting black pixels
  137. if (currentState == 4)
  138. {
  139. // A winner?
  140. if (foundPatternCross(stateCount))
  141. {
  142. // Yes
  143. bool confirmed = handlePossibleCenter(stateCount, i, j);
  144. if (confirmed)
  145. {
  146. // Start examining every other line. Checking each line turned out to be too
  147. // expensive and didn't improve performance.
  148. iSkip = 2;
  149. if (hasSkipped)
  150. {
  151. done = haveMultiplyConfirmedCenters();
  152. }
  153. else
  154. {
  155. int rowSkip = findRowSkip();
  156. if (rowSkip > stateCount[2])
  157. {
  158. // Skip rows between row of lower confirmed center
  159. // and top of presumed third confirmed center
  160. // but back up a bit to get a full chance of detecting
  161. // it, entire width of center of finder pattern
  162. // Skip by rowSkip, but back off by stateCount[2] (size of last center
  163. // of pattern we saw) to be conservative, and also back off by iSkip which
  164. // is about to be re-added
  165. i += rowSkip - stateCount[2] - iSkip;
  166. j = maxJ - 1;
  167. }
  168. }
  169. }
  170. else
  171. {
  172. // Advance to next black pixel
  173. do
  174. {
  175. j++;
  176. }
  177. while (j < maxJ && !image.get_Renamed(j, i));
  178. j--; // back up to that last white pixel
  179. }
  180. // Clear state to start looking again
  181. currentState = 0;
  182. stateCount[0] = 0;
  183. stateCount[1] = 0;
  184. stateCount[2] = 0;
  185. stateCount[3] = 0;
  186. stateCount[4] = 0;
  187. }
  188. else
  189. {
  190. // No, shift counts back by two
  191. stateCount[0] = stateCount[2];
  192. stateCount[1] = stateCount[3];
  193. stateCount[2] = stateCount[4];
  194. stateCount[3] = 1;
  195. stateCount[4] = 0;
  196. currentState = 3;
  197. }
  198. }
  199. else
  200. {
  201. stateCount[++currentState]++;
  202. }
  203. }
  204. else
  205. {
  206. // Counting white pixels
  207. stateCount[currentState]++;
  208. }
  209. }
  210. }
  211. if (foundPatternCross(stateCount))
  212. {
  213. bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
  214. if (confirmed)
  215. {
  216. iSkip = stateCount[0];
  217. if (hasSkipped)
  218. {
  219. // Found a third one
  220. done = haveMultiplyConfirmedCenters();
  221. }
  222. }
  223. }
  224. }
  225. FinderPattern[] patternInfo = selectBestPatterns();
  226. ResultPoint.orderBestPatterns(patternInfo);
  227. return new FinderPatternInfo(patternInfo);
  228. }
  229. /// <summary> Given a count of black/white/black/white/black pixels just seen and an end position,
  230. /// figures the location of the center of this run.
  231. /// </summary>
  232. private static float centerFromEnd(int[] stateCount, int end)
  233. {
  234. //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'"
  235. return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
  236. }
  237. /// <param name="stateCount">count of black/white/black/white/black pixels just read
  238. /// </param>
  239. /// <returns> true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
  240. /// used by finder patterns to be considered a match
  241. /// </returns>
  242. protected internal static bool foundPatternCross(int[] stateCount)
  243. {
  244. int totalModuleSize = 0;
  245. for (int i = 0; i < 5; i++)
  246. {
  247. int count = stateCount[i];
  248. if (count == 0)
  249. {
  250. return false;
  251. }
  252. totalModuleSize += count;
  253. }
  254. if (totalModuleSize < 7)
  255. {
  256. return false;
  257. }
  258. int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
  259. int maxVariance = moduleSize / 2;
  260. // Allow less than 50% variance from 1-1-3-1-1 proportions
  261. return System.Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && System.Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
  262. }
  263. /// <summary> <p>After a horizontal scan finds a potential finder pattern, this method
  264. /// "cross-checks" by scanning down vertically through the center of the possible
  265. /// finder pattern to see if the same proportion is detected.</p>
  266. ///
  267. /// </summary>
  268. /// <param name="startI">row where a finder pattern was detected
  269. /// </param>
  270. /// <param name="centerJ">center of the section that appears to cross a finder pattern
  271. /// </param>
  272. /// <param name="maxCount">maximum reasonable number of modules that should be
  273. /// observed in any reading state, based on the results of the horizontal scan
  274. /// </param>
  275. /// <returns> vertical center of finder pattern, or {@link Float#NaN} if not found
  276. /// </returns>
  277. private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
  278. {
  279. BitMatrix image = this.image;
  280. int maxI = image.Height;
  281. int[] stateCount = CrossCheckStateCount;
  282. // Start counting up from center
  283. int i = startI;
  284. while (i >= 0 && image.get_Renamed(centerJ, i))
  285. {
  286. stateCount[2]++;
  287. i--;
  288. }
  289. if (i < 0)
  290. {
  291. return System.Single.NaN;
  292. }
  293. while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
  294. {
  295. stateCount[1]++;
  296. i--;
  297. }
  298. // If already too many modules in this state or ran off the edge:
  299. if (i < 0 || stateCount[1] > maxCount)
  300. {
  301. return System.Single.NaN;
  302. }
  303. while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
  304. {
  305. stateCount[0]++;
  306. i--;
  307. }
  308. if (stateCount[0] > maxCount)
  309. {
  310. return System.Single.NaN;
  311. }
  312. // Now also count down from center
  313. i = startI + 1;
  314. while (i < maxI && image.get_Renamed(centerJ, i))
  315. {
  316. stateCount[2]++;
  317. i++;
  318. }
  319. if (i == maxI)
  320. {
  321. return System.Single.NaN;
  322. }
  323. while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[3] < maxCount)
  324. {
  325. stateCount[3]++;
  326. i++;
  327. }
  328. if (i == maxI || stateCount[3] >= maxCount)
  329. {
  330. return System.Single.NaN;
  331. }
  332. while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[4] < maxCount)
  333. {
  334. stateCount[4]++;
  335. i++;
  336. }
  337. if (stateCount[4] >= maxCount)
  338. {
  339. return System.Single.NaN;
  340. }
  341. // If we found a finder-pattern-like section, but its size is more than 40% different than
  342. // the original, assume it's a false positive
  343. int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
  344. if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
  345. {
  346. return System.Single.NaN;
  347. }
  348. return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
  349. }
  350. /// <summary> <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
  351. /// except it reads horizontally instead of vertically. This is used to cross-cross
  352. /// check a vertical cross check and locate the real center of the alignment pattern.</p>
  353. /// </summary>
  354. private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal)
  355. {
  356. BitMatrix image = this.image;
  357. int maxJ = image.Width;
  358. int[] stateCount = CrossCheckStateCount;
  359. int j = startJ;
  360. while (j >= 0 && image.get_Renamed(j, centerI))
  361. {
  362. stateCount[2]++;
  363. j--;
  364. }
  365. if (j < 0)
  366. {
  367. return System.Single.NaN;
  368. }
  369. while (j >= 0 && !image.get_Renamed(j, centerI) && stateCount[1] <= maxCount)
  370. {
  371. stateCount[1]++;
  372. j--;
  373. }
  374. if (j < 0 || stateCount[1] > maxCount)
  375. {
  376. return System.Single.NaN;
  377. }
  378. while (j >= 0 && image.get_Renamed(j, centerI) && stateCount[0] <= maxCount)
  379. {
  380. stateCount[0]++;
  381. j--;
  382. }
  383. if (stateCount[0] > maxCount)
  384. {
  385. return System.Single.NaN;
  386. }
  387. j = startJ + 1;
  388. while (j < maxJ && image.get_Renamed(j, centerI))
  389. {
  390. stateCount[2]++;
  391. j++;
  392. }
  393. if (j == maxJ)
  394. {
  395. return System.Single.NaN;
  396. }
  397. while (j < maxJ && !image.get_Renamed(j, centerI) && stateCount[3] < maxCount)
  398. {
  399. stateCount[3]++;
  400. j++;
  401. }
  402. if (j == maxJ || stateCount[3] >= maxCount)
  403. {
  404. return System.Single.NaN;
  405. }
  406. while (j < maxJ && image.get_Renamed(j, centerI) && stateCount[4] < maxCount)
  407. {
  408. stateCount[4]++;
  409. j++;
  410. }
  411. if (stateCount[4] >= maxCount)
  412. {
  413. return System.Single.NaN;
  414. }
  415. // If we found a finder-pattern-like section, but its size is significantly different than
  416. // the original, assume it's a false positive
  417. int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
  418. if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
  419. {
  420. return System.Single.NaN;
  421. }
  422. return foundPatternCross(stateCount)?centerFromEnd(stateCount, j):System.Single.NaN;
  423. }
  424. /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  425. /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check
  426. /// with another horizontal scan. This is needed primarily to locate the real horizontal
  427. /// center of the pattern in cases of extreme skew.</p>
  428. ///
  429. /// <p>If that succeeds the finder pattern location is added to a list that tracks
  430. /// the number of times each location has been nearly-matched as a finder pattern.
  431. /// Each additional find is more evidence that the location is in fact a finder
  432. /// pattern center
  433. ///
  434. /// </summary>
  435. /// <param name="stateCount">reading state module counts from horizontal scan
  436. /// </param>
  437. /// <param name="i">row where finder pattern may be found
  438. /// </param>
  439. /// <param name="j">end of possible finder pattern in row
  440. /// </param>
  441. /// <returns> true if a finder pattern candidate was found this time
  442. /// </returns>
  443. protected internal virtual bool handlePossibleCenter(int[] stateCount, int i, int j)
  444. {
  445. int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
  446. float centerJ = centerFromEnd(stateCount, j);
  447. //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'"
  448. float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
  449. if (!System.Single.IsNaN(centerI))
  450. {
  451. // Re-cross check
  452. //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'"
  453. centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
  454. if (!System.Single.IsNaN(centerJ))
  455. {
  456. //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'"
  457. float estimatedModuleSize = (float) stateCountTotal / 7.0f;
  458. bool found = false;
  459. int max = possibleCenters.Count;
  460. for (int index = 0; index < max; index++)
  461. {
  462. FinderPattern center = (FinderPattern) possibleCenters[index];
  463. // Look for about the same center and module size:
  464. if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
  465. {
  466. center.incrementCount();
  467. found = true;
  468. break;
  469. }
  470. }
  471. if (!found)
  472. {
  473. ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
  474. possibleCenters.Add(point);
  475. if (resultPointCallback != null)
  476. {
  477. resultPointCallback.foundPossibleResultPoint(point);
  478. }
  479. }
  480. return true;
  481. }
  482. }
  483. return false;
  484. }
  485. /// <returns> number of rows we could safely skip during scanning, based on the first
  486. /// two finder patterns that have been located. In some cases their position will
  487. /// allow us to infer that the third pattern must lie below a certain point farther
  488. /// down in the image.
  489. /// </returns>
  490. private int findRowSkip()
  491. {
  492. int max = possibleCenters.Count;
  493. if (max <= 1)
  494. {
  495. return 0;
  496. }
  497. FinderPattern firstConfirmedCenter = null;
  498. for (int i = 0; i < max; i++)
  499. {
  500. FinderPattern center = (FinderPattern) possibleCenters[i];
  501. if (center.Count >= CENTER_QUORUM)
  502. {
  503. if (firstConfirmedCenter == null)
  504. {
  505. firstConfirmedCenter = center;
  506. }
  507. else
  508. {
  509. // We have two confirmed centers
  510. // How far down can we skip before resuming looking for the next
  511. // pattern? In the worst case, only the difference between the
  512. // difference in the x / y coordinates of the two centers.
  513. // This is the case where you find top left last.
  514. hasSkipped = true;
  515. //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'"
  516. return (int) (System.Math.Abs(firstConfirmedCenter.X - center.X) - System.Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2;
  517. }
  518. }
  519. }
  520. return 0;
  521. }
  522. /// <returns> true iff we have found at least 3 finder patterns that have been detected
  523. /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
  524. /// candidates is "pretty similar"
  525. /// </returns>
  526. private bool haveMultiplyConfirmedCenters()
  527. {
  528. int confirmedCount = 0;
  529. float totalModuleSize = 0.0f;
  530. int max = possibleCenters.Count;
  531. for (int i = 0; i < max; i++)
  532. {
  533. FinderPattern pattern = (FinderPattern) possibleCenters[i];
  534. if (pattern.Count >= CENTER_QUORUM)
  535. {
  536. confirmedCount++;
  537. totalModuleSize += pattern.EstimatedModuleSize;
  538. }
  539. }
  540. if (confirmedCount < 3)
  541. {
  542. return false;
  543. }
  544. // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
  545. // and that we need to keep looking. We detect this by asking if the estimated module sizes
  546. // vary too much. We arbitrarily say that when the total deviation from average exceeds
  547. // 5% of the total module size estimates, it's too much.
  548. //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'"
  549. float average = totalModuleSize / (float) max;
  550. float totalDeviation = 0.0f;
  551. for (int i = 0; i < max; i++)
  552. {
  553. FinderPattern pattern = (FinderPattern) possibleCenters[i];
  554. totalDeviation += System.Math.Abs(pattern.EstimatedModuleSize - average);
  555. }
  556. return totalDeviation <= 0.05f * totalModuleSize;
  557. }
  558. /// <returns> the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
  559. /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
  560. /// size differs from the average among those patterns the least
  561. /// </returns>
  562. /// <throws> ReaderException if 3 such finder patterns do not exist </throws>
  563. private FinderPattern[] selectBestPatterns()
  564. {
  565. int startSize = possibleCenters.Count;
  566. if (startSize < 3)
  567. {
  568. // Couldn't find enough finder patterns
  569. throw ReaderException.Instance;
  570. }
  571. // Filter outlier possibilities whose module size is too different
  572. if (startSize > 3)
  573. {
  574. // But we can only afford to do so if we have at least 4 possibilities to choose from
  575. float totalModuleSize = 0.0f;
  576. for (int i = 0; i < startSize; i++)
  577. {
  578. totalModuleSize += ((FinderPattern) possibleCenters[i]).EstimatedModuleSize;
  579. }
  580. //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'"
  581. float average = totalModuleSize / (float) startSize;
  582. for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++)
  583. {
  584. FinderPattern pattern = (FinderPattern) possibleCenters[i];
  585. if (System.Math.Abs(pattern.EstimatedModuleSize - average) > 0.2f * average)
  586. {
  587. possibleCenters.RemoveAt(i);
  588. i--;
  589. }
  590. }
  591. }
  592. if (possibleCenters.Count > 3)
  593. {
  594. // Throw away all but those first size candidate points we found.
  595. Collections.insertionSort(possibleCenters, new CenterComparator());
  596. SupportClass.SetCapacity(possibleCenters, 3);
  597. }
  598. return new FinderPattern[]{(FinderPattern) possibleCenters[0], (FinderPattern) possibleCenters[1], (FinderPattern) possibleCenters[2]};
  599. }
  600. /// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary>
  601. private class CenterComparator : Comparator
  602. {
  603. public virtual int compare(System.Object center1, System.Object center2)
  604. {
  605. return ((FinderPattern) center2).Count - ((FinderPattern) center1).Count;
  606. }
  607. }
  608. }
  609. }