You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ZXMultiFinderPatternFinder.m 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Copyright 2012 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. #import "ZXBitMatrix.h"
  17. #import "ZXDecodeHints.h"
  18. #import "ZXErrors.h"
  19. #import "ZXMultiFinderPatternFinder.h"
  20. #import "ZXQRCodeFinderPattern.h"
  21. #import "ZXQRCodeFinderPatternInfo.h"
  22. // TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for
  23. // since it limits the number of regions to decode
  24. // max. legal count of modules per QR code edge (177)
  25. float const ZX_MAX_MODULE_COUNT_PER_EDGE = 180;
  26. // min. legal count per modules per QR code edge (11)
  27. float const ZX_MIN_MODULE_COUNT_PER_EDGE = 9;
  28. /**
  29. * More or less arbitrary cutoff point for determining if two finder patterns might belong
  30. * to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their
  31. * estimated modules sizes.
  32. */
  33. float const ZX_DIFF_MODSIZE_CUTOFF_PERCENT = 0.05f;
  34. /**
  35. * More or less arbitrary cutoff point for determining if two finder patterns might belong
  36. * to the same code if they differ less than DIFF_MODSIZE_CUTOFF pixels/module in their
  37. * estimated modules sizes.
  38. */
  39. float const ZX_DIFF_MODSIZE_CUTOFF = 0.5f;
  40. @implementation ZXMultiFinderPatternFinder
  41. /**
  42. * Returns the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
  43. * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
  44. * size differs from the average among those patterns the least
  45. */
  46. - (NSArray *)selectBestPatternsWithError:(NSError **)error {
  47. NSMutableArray *_possibleCenters = [NSMutableArray arrayWithArray:[self possibleCenters]];
  48. NSUInteger size = [_possibleCenters count];
  49. if (size < 3) {
  50. if (error) *error = ZXNotFoundErrorInstance();
  51. return nil;
  52. }
  53. /*
  54. * Begin HE modifications to safely detect multiple codes of equal size
  55. */
  56. if (size == 3) {
  57. return @[[@[_possibleCenters[0], _possibleCenters[1], _possibleCenters[2]] mutableCopy]];
  58. }
  59. [_possibleCenters sortUsingFunction:moduleSizeCompare context:nil];
  60. /*
  61. * Now lets start: build a list of tuples of three finder locations that
  62. * - feature similar module sizes
  63. * - are placed in a distance so the estimated module count is within the QR specification
  64. * - have similar distance between upper left/right and left top/bottom finder patterns
  65. * - form a triangle with 90° angle (checked by comparing top right/bottom left distance
  66. * with pythagoras)
  67. *
  68. * Note: we allow each point to be used for more than one code region: this might seem
  69. * counterintuitive at first, but the performance penalty is not that big. At this point,
  70. * we cannot make a good quality decision whether the three finders actually represent
  71. * a QR code, or are just by chance layouted so it looks like there might be a QR code there.
  72. * So, if the layout seems right, lets have the decoder try to decode.
  73. */
  74. NSMutableArray *results = [NSMutableArray array];
  75. for (int i1 = 0; i1 < (size - 2); i1++) {
  76. ZXQRCodeFinderPattern *p1 = self.possibleCenters[i1];
  77. if (p1 == nil) {
  78. continue;
  79. }
  80. for (int i2 = i1 + 1; i2 < (size - 1); i2++) {
  81. ZXQRCodeFinderPattern *p2 = self.possibleCenters[i2];
  82. if (p2 == nil) {
  83. continue;
  84. }
  85. float vModSize12 = ([p1 estimatedModuleSize] - [p2 estimatedModuleSize]) / MIN([p1 estimatedModuleSize], [p2 estimatedModuleSize]);
  86. float vModSize12A = fabsf([p1 estimatedModuleSize] - [p2 estimatedModuleSize]);
  87. if (vModSize12A > ZX_DIFF_MODSIZE_CUTOFF && vModSize12 >= ZX_DIFF_MODSIZE_CUTOFF_PERCENT) {
  88. break;
  89. }
  90. for (int i3 = i2 + 1; i3 < size; i3++) {
  91. ZXQRCodeFinderPattern *p3 = self.possibleCenters[i3];
  92. if (p3 == nil) {
  93. continue;
  94. }
  95. float vModSize23 = ([p2 estimatedModuleSize] - [p3 estimatedModuleSize]) / MIN([p2 estimatedModuleSize], [p3 estimatedModuleSize]);
  96. float vModSize23A = fabsf([p2 estimatedModuleSize] - [p3 estimatedModuleSize]);
  97. if (vModSize23A > ZX_DIFF_MODSIZE_CUTOFF && vModSize23 >= ZX_DIFF_MODSIZE_CUTOFF_PERCENT) {
  98. break;
  99. }
  100. NSMutableArray *test = [NSMutableArray arrayWithObjects:p1, p2, p3, nil];
  101. [ZXResultPoint orderBestPatterns:test];
  102. ZXQRCodeFinderPatternInfo *info = [[ZXQRCodeFinderPatternInfo alloc] initWithPatternCenters:test];
  103. float dA = [ZXResultPoint distance:[info topLeft] pattern2:[info bottomLeft]];
  104. float dC = [ZXResultPoint distance:[info topRight] pattern2:[info bottomLeft]];
  105. float dB = [ZXResultPoint distance:[info topLeft] pattern2:[info topRight]];
  106. float estimatedModuleCount = (dA + dB) / ([p1 estimatedModuleSize] * 2.0f);
  107. if (estimatedModuleCount > ZX_MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < ZX_MIN_MODULE_COUNT_PER_EDGE) {
  108. continue;
  109. }
  110. float vABBC = fabsf((dA - dB) / MIN(dA, dB));
  111. if (vABBC >= 0.1f) {
  112. continue;
  113. }
  114. float dCpy = (float)sqrt(dA * dA + dB * dB);
  115. float vPyC = fabsf((dC - dCpy) / MIN(dC, dCpy));
  116. if (vPyC >= 0.1f) {
  117. continue;
  118. }
  119. [results addObject:test];
  120. }
  121. }
  122. }
  123. if ([results count] > 0) {
  124. return results;
  125. }
  126. if (error) *error = ZXNotFoundErrorInstance();
  127. return nil;
  128. }
  129. - (NSArray *)findMulti:(ZXDecodeHints *)hints error:(NSError **)error {
  130. BOOL tryHarder = hints != nil && hints.tryHarder;
  131. BOOL pureBarcode = hints != nil && hints.pureBarcode;
  132. int maxI = self.image.height;
  133. int maxJ = self.image.width;
  134. // We are looking for black/white/black/white/black modules in
  135. // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
  136. // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  137. // image, and then account for the center being 3 modules in size. This gives the smallest
  138. // number of pixels the center could be, so skip this often. When trying harder, look for all
  139. // QR versions regardless of how dense they are.
  140. int iSkip = (int)(maxI / (ZX_FINDER_PATTERN_MAX_MODULES * 4.0f) * 3);
  141. if (iSkip < ZX_FINDER_PATTERN_MIN_SKIP || tryHarder) {
  142. iSkip = ZX_FINDER_PATTERN_MIN_SKIP;
  143. }
  144. int stateCount[5];
  145. for (int i = iSkip - 1; i < maxI; i += iSkip) {
  146. stateCount[0] = 0;
  147. stateCount[1] = 0;
  148. stateCount[2] = 0;
  149. stateCount[3] = 0;
  150. stateCount[4] = 0;
  151. int currentState = 0;
  152. for (int j = 0; j < maxJ; j++) {
  153. if ([self.image getX:j y:i]) {
  154. if ((currentState & 1) == 1) {
  155. currentState++;
  156. }
  157. stateCount[currentState]++;
  158. } else {
  159. if ((currentState & 1) == 0) {
  160. if (currentState == 4) {
  161. if ([ZXQRCodeFinderPatternFinder foundPatternCross:stateCount] && [self handlePossibleCenter:stateCount i:i j:j pureBarcode:pureBarcode]) {
  162. currentState = 0;
  163. stateCount[0] = 0;
  164. stateCount[1] = 0;
  165. stateCount[2] = 0;
  166. stateCount[3] = 0;
  167. stateCount[4] = 0;
  168. } else {
  169. stateCount[0] = stateCount[2];
  170. stateCount[1] = stateCount[3];
  171. stateCount[2] = stateCount[4];
  172. stateCount[3] = 1;
  173. stateCount[4] = 0;
  174. currentState = 3;
  175. }
  176. } else {
  177. stateCount[++currentState]++;
  178. }
  179. } else {
  180. stateCount[currentState]++;
  181. }
  182. }
  183. }
  184. if ([ZXQRCodeFinderPatternFinder foundPatternCross:stateCount]) {
  185. [self handlePossibleCenter:stateCount i:i j:maxJ pureBarcode:pureBarcode];
  186. }
  187. }
  188. NSArray *patternInfo = [self selectBestPatternsWithError:error];
  189. if (!patternInfo) {
  190. return nil;
  191. }
  192. NSMutableArray *result = [NSMutableArray array];
  193. for (NSMutableArray *pattern in patternInfo) {
  194. [ZXResultPoint orderBestPatterns:pattern];
  195. [result addObject:[[ZXQRCodeFinderPatternInfo alloc] initWithPatternCenters:pattern]];
  196. }
  197. return result;
  198. }
  199. /**
  200. * A comparator that orders FinderPatterns by their estimated module size.
  201. */
  202. NSInteger moduleSizeCompare(id center1, id center2, void *context) {
  203. float value = [((ZXQRCodeFinderPattern *)center2) estimatedModuleSize] - [((ZXQRCodeFinderPattern *)center1) estimatedModuleSize];
  204. return value < 0.0 ? -1 : value > 0.0 ? 1 : 0;
  205. }
  206. @end