Many changes to the C++ port.
[zxing.git] / cpp / core / src / zxing / qrcode / detector / FinderPatternFinder.cpp
1 /*
2  *  FinderPatternFinder.cpp
3  *  zxing
4  *
5  *  Created by Christian Brunschen on 13/05/2008.
6  *  Copyright 2008 ZXing authors All rights reserved.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 #include <zxing/qrcode/detector/FinderPatternFinder.h>
22 #include <zxing/ReaderException.h>
23 #include <vector>
24 #include <cmath>
25
26 namespace zxing {
27 namespace qrcode {
28
29 using namespace std;
30
31 class ClosestToAverageComparator {
32 private:
33   float averageModuleSize_;
34 public:
35   ClosestToAverageComparator(float averageModuleSize) :
36       averageModuleSize_(averageModuleSize) {
37   }
38   int operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
39     float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_);
40     float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_);
41     return dA < dB ? -1 : dA > dB ? 1 : 0;
42   }
43 };
44
45 class CenterComparator {
46 public:
47   int operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
48     return b->getCount() - a->getCount();
49   }
50 };
51
52 int FinderPatternFinder::CENTER_QUORUM = 2;
53 int FinderPatternFinder::MIN_SKIP = 3;
54 int FinderPatternFinder::MAX_MODULES = 57;
55
56 float FinderPatternFinder::centerFromEnd(int* stateCount, int end) {
57   return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
58 }
59
60 bool FinderPatternFinder::foundPatternCross(int* stateCount) {
61   int totalModuleSize = 0;
62   for (int i = 0; i < 5; i++) {
63     if (stateCount[i] == 0) {
64       return false;
65     }
66     totalModuleSize += stateCount[i];
67   }
68   if (totalModuleSize < 7) {
69     return false;
70   }
71   float moduleSize = (float)totalModuleSize / 7.0f;
72   float maxVariance = moduleSize / 2.0f;
73   // Allow less than 50% variance from 1-1-3-1-1 proportions
74   return abs(moduleSize - stateCount[0]) < maxVariance && abs(moduleSize - stateCount[1]) < maxVariance && abs(3.0f
75          * moduleSize - stateCount[2]) < 3.0f * maxVariance && abs(moduleSize - stateCount[3]) < maxVariance && abs(
76            moduleSize - stateCount[4]) < maxVariance;
77 }
78
79 float FinderPatternFinder::crossCheckVertical(size_t startI, size_t centerJ, int maxCount, int originalStateCountTotal) {
80
81   int maxI = image_->getHeight();
82   int stateCount[5];
83   for (int i = 0; i < 5; i++)
84     stateCount[i] = 0;
85
86
87   // Start counting up from center
88   int i = startI;
89   while (i >= 0 && image_->get(centerJ, i)) {
90     stateCount[2]++;
91     i--;
92   }
93   if (i < 0) {
94     return NAN;
95   }
96   while (i >= 0 && !image_->get(centerJ, i) && stateCount[1] <= maxCount) {
97     stateCount[1]++;
98     i--;
99   }
100   // If already too many modules in this state or ran off the edge:
101   if (i < 0 || stateCount[1] > maxCount) {
102     return NAN;
103   }
104   while (i >= 0 && image_->get(centerJ, i) && stateCount[0] <= maxCount) {
105     stateCount[0]++;
106     i--;
107   }
108   if (stateCount[0] > maxCount) {
109     return NAN;
110   }
111
112   // Now also count down from center
113   i = startI + 1;
114   while (i < maxI && image_->get(centerJ, i)) {
115     stateCount[2]++;
116     i++;
117   }
118   if (i == maxI) {
119     return NAN;
120   }
121   while (i < maxI && !image_->get(centerJ, i) && stateCount[3] < maxCount) {
122     stateCount[3]++;
123     i++;
124   }
125   if (i == maxI || stateCount[3] >= maxCount) {
126     return NAN;
127   }
128   while (i < maxI && image_->get(centerJ, i) && stateCount[4] < maxCount) {
129     stateCount[4]++;
130     i++;
131   }
132   if (stateCount[4] >= maxCount) {
133     return NAN;
134   }
135
136   // If we found a finder-pattern-like section, but its size is more than 20% different than
137   // the original, assume it's a false positive
138   int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
139   if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
140     return NAN;
141   }
142
143   return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : NAN;
144 }
145
146 float FinderPatternFinder::crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount,
147     int originalStateCountTotal) {
148
149   int maxJ = image_->getWidth();
150   int stateCount[5];
151   for (int i = 0; i < 5; i++)
152     stateCount[i] = 0;
153
154   int j = startJ;
155   while (j >= 0 && image_->get(j, centerI)) {
156     stateCount[2]++;
157     j--;
158   }
159   if (j < 0) {
160     return NAN;
161   }
162   while (j >= 0 && !image_->get(j, centerI) && stateCount[1] <= maxCount) {
163     stateCount[1]++;
164     j--;
165   }
166   if (j < 0 || stateCount[1] > maxCount) {
167     return NAN;
168   }
169   while (j >= 0 && image_->get(j, centerI) && stateCount[0] <= maxCount) {
170     stateCount[0]++;
171     j--;
172   }
173   if (stateCount[0] > maxCount) {
174     return NAN;
175   }
176
177   j = startJ + 1;
178   while (j < maxJ && image_->get(j, centerI)) {
179     stateCount[2]++;
180     j++;
181   }
182   if (j == maxJ) {
183     return NAN;
184   }
185   while (j < maxJ && !image_->get(j, centerI) && stateCount[3] < maxCount) {
186     stateCount[3]++;
187     j++;
188   }
189   if (j == maxJ || stateCount[3] >= maxCount) {
190     return NAN;
191   }
192   while (j < maxJ && image_->get(j, centerI) && stateCount[4] < maxCount) {
193     stateCount[4]++;
194     j++;
195   }
196   if (stateCount[4] >= maxCount) {
197     return NAN;
198   }
199
200   // If we found a finder-pattern-like section, but its size is significantly different than
201   // the original, assume it's a false positive
202   int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
203   if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
204     return NAN;
205   }
206
207   return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : NAN;
208 }
209
210 bool FinderPatternFinder::handlePossibleCenter(int* stateCount, size_t i, size_t j) {
211   int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
212   float centerJ = centerFromEnd(stateCount, j);
213   float centerI = crossCheckVertical(i, (size_t)centerJ, stateCount[2], stateCountTotal);
214   if (!isnan(centerI)) {
215     // Re-cross check
216     centerJ = crossCheckHorizontal((size_t)centerJ, (size_t)centerI, stateCount[2], stateCountTotal);
217     if (!isnan(centerJ)) {
218       float estimatedModuleSize = (float)stateCountTotal / 7.0f;
219       bool found = false;
220       size_t max = possibleCenters_.size();
221       for (size_t index = 0; index < max; index++) {
222         Ref<FinderPattern> center = possibleCenters_[index];
223         // Look for about the same center and module size:
224         if (center->aboutEquals(estimatedModuleSize, centerI, centerJ)) {
225           center->incrementCount();
226           found = true;
227           break;
228         }
229       }
230       if (!found) {
231         Ref<FinderPattern> newPattern(new FinderPattern(centerJ, centerI, estimatedModuleSize));
232         possibleCenters_.push_back(newPattern);
233       }
234       return true;
235     }
236   }
237   return false;
238 }
239
240 int FinderPatternFinder::findRowSkip() {
241   size_t max = possibleCenters_.size();
242   if (max <= 1) {
243     return 0;
244   }
245   Ref<FinderPattern> firstConfirmedCenter;
246   for (size_t i = 0; i < max; i++) {
247     Ref<FinderPattern> center = possibleCenters_[i];
248     if (center->getCount() >= CENTER_QUORUM) {
249       if (firstConfirmedCenter == 0) {
250         firstConfirmedCenter = center;
251       } else {
252         // We have two confirmed centers
253         // How far down can we skip before resuming looking for the next
254         // pattern? In the worst case, only the difference between the
255         // difference in the x / y coordinates of the two centers.
256         // This is the case where you find top left first. Draw it out.
257         hasSkipped_ = true;
258         return (int)(abs(firstConfirmedCenter->getX() - center->getX()) - abs(firstConfirmedCenter->getY()
259                      - center->getY()));
260       }
261     }
262   }
263   return 0;
264 }
265
266 bool FinderPatternFinder::haveMultiplyConfirmedCenters() {
267   int confirmedCount = 0;
268   float totalModuleSize = 0.0f;
269   size_t max = possibleCenters_.size();
270   for (size_t i = 0; i < max; i++) {
271     Ref<FinderPattern> pattern = possibleCenters_[i];
272     if (pattern->getCount() >= CENTER_QUORUM) {
273       confirmedCount++;
274       totalModuleSize += pattern->getEstimatedModuleSize();
275     }
276   }
277   if (confirmedCount < 3) {
278     return false;
279   }
280   // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
281   // and that we need to keep looking. We detect this by asking if the estimated module sizes
282   // vary too much. We arbitrarily say that when the total deviation from average exceeds
283   // 15% of the total module size estimates, it's too much.
284   float average = totalModuleSize / max;
285   float totalDeviation = 0.0f;
286   for (size_t i = 0; i < max; i++) {
287     Ref<FinderPattern> pattern = possibleCenters_[i];
288     totalDeviation += abs(pattern->getEstimatedModuleSize() - average);
289   }
290   return totalDeviation <= 0.15f * totalModuleSize;
291 }
292
293 vector<Ref<FinderPattern> > FinderPatternFinder::selectBestPatterns() {
294   sort(possibleCenters_.begin(), possibleCenters_.end(), CenterComparator());
295   size_t size = 0;
296   size_t max = possibleCenters_.size();
297   while (size < max) {
298     if (possibleCenters_[size]->getCount() < CENTER_QUORUM) {
299       break;
300     }
301     size++;
302   }
303
304   if (size < 3) {
305     // Couldn't find enough finder patterns
306     throw zxing::ReaderException("Could not find three finder patterns");
307   }
308
309   if (size == 3) {
310     // Found just enough -- hope these are good!
311     vector<Ref<FinderPattern> > result(3);
312     result[0] = possibleCenters_[0];
313     result[1] = possibleCenters_[1];
314     result[2] = possibleCenters_[2];
315     return result;
316   }
317
318   // Hmm, multiple found. We need to pick the best three. Find the most
319   // popular ones whose module size is nearest the average
320   // This does not work for multiple qr codes in the same image
321   float averageModuleSize = 0.0f;
322   for (size_t i = 0; i < size; i++) {
323     averageModuleSize += possibleCenters_[i]->getEstimatedModuleSize();
324   }
325   averageModuleSize /= (float)size;
326
327   sort(possibleCenters_.begin(), possibleCenters_.end(), ClosestToAverageComparator(averageModuleSize));
328
329   vector<Ref<FinderPattern> > result(3);
330   result[0] = possibleCenters_[0];
331   result[1] = possibleCenters_[1];
332   result[2] = possibleCenters_[2];
333   return result;
334 }
335
336 vector<Ref<FinderPattern> > FinderPatternFinder::orderBestPatterns(vector<Ref<FinderPattern> > patterns) {
337   // Find distances between pattern centers
338   float abDistance = distance(patterns[0], patterns[1]);
339   float bcDistance = distance(patterns[1], patterns[2]);
340   float acDistance = distance(patterns[0], patterns[2]);
341
342   Ref<FinderPattern> topLeft;
343   Ref<FinderPattern> topRight;
344   Ref<FinderPattern> bottomLeft;
345   // Assume one closest to other two is top left;
346   // topRight and bottomLeft will just be guesses below at first
347   if (bcDistance >= abDistance && bcDistance >= acDistance) {
348     topLeft = patterns[0];
349     topRight = patterns[1];
350     bottomLeft = patterns[2];
351   } else if (acDistance >= bcDistance && acDistance >= abDistance) {
352     topLeft = patterns[1];
353     topRight = patterns[0];
354     bottomLeft = patterns[2];
355   } else {
356     topLeft = patterns[2];
357     topRight = patterns[0];
358     bottomLeft = patterns[1];
359   }
360
361   // Use cross product to figure out which of other1/2 is the bottom left
362   // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right"
363   // should yield a vector with positive z component
364   if ((bottomLeft->getY() - topLeft->getY()) * (topRight->getX() - topLeft->getX()) < (bottomLeft->getX()
365       - topLeft->getX()) * (topRight->getY() - topLeft->getY())) {
366     Ref<FinderPattern> temp = topRight;
367     topRight = bottomLeft;
368     bottomLeft = temp;
369   }
370
371   vector<Ref<FinderPattern> > results(3);
372   results[0] = bottomLeft;
373   results[1] = topLeft;
374   results[2] = topRight;
375   return results;
376 }
377
378 float FinderPatternFinder::distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2) {
379   float dx = p1->getX() - p2->getX();
380   float dy = p1->getY() - p2->getY();
381   return (float)sqrt(dx * dx + dy * dy);
382 }
383
384 FinderPatternFinder::FinderPatternFinder(Ref<BitMatrix> image) :
385     image_(image), possibleCenters_(), hasSkipped_(false) {
386 }
387
388 Ref<FinderPatternInfo> FinderPatternFinder::find() {
389   size_t maxI = image_->getHeight();
390   size_t maxJ = image_->getWidth();
391
392
393   // We are looking for black/white/black/white/black modules in
394   // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
395
396   // As this is used often, we use an integer array instead of valarray
397   int stateCount[5];
398   bool done = false;
399
400
401   // Let's assume that the maximum version QR Code we support takes up 1/4
402   // the height of the image, and then account for the center being 3
403   // modules in size. This gives the smallest number of pixels the center
404   // could be, so skip this often. When trying harder, look for all
405   // QR versions regardless of how dense they are.
406   size_t iSkip = MIN_SKIP;
407
408   // This is slightly faster than using the Ref. Efficiency is important here
409   BitMatrix& matrix = *image_;
410
411   for (size_t i = iSkip - 1; i < maxI && !done; i += iSkip) {
412     // Get a row of black/white values
413
414     stateCount[0] = 0;
415     stateCount[1] = 0;
416     stateCount[2] = 0;
417     stateCount[3] = 0;
418     stateCount[4] = 0;
419     int currentState = 0;
420     for (size_t j = 0; j < maxJ; j++) {
421       if (matrix.get(j, i)) {
422         // Black pixel
423         if ((currentState & 1) == 1) { // Counting white pixels
424           currentState++;
425         }
426         stateCount[currentState]++;
427       } else { // White pixel
428         if ((currentState & 1) == 0) { // Counting black pixels
429           if (currentState == 4) { // A winner?
430             if (foundPatternCross(stateCount)) { // Yes
431               bool confirmed = handlePossibleCenter(stateCount, i, j);
432               if (confirmed) {
433                 iSkip = 1; // Go back to examining each line
434                 if (hasSkipped_) {
435                   done = haveMultiplyConfirmedCenters();
436                 } else {
437                   int rowSkip = findRowSkip();
438                   if (rowSkip > stateCount[2]) {
439                     // Skip rows between row of lower confirmed center
440                     // and top of presumed third confirmed center
441                     // but back up a bit to get a full chance of detecting
442                     // it, entire width of center of finder pattern
443
444                     // Skip by rowSkip, but back off by stateCount[2] (size
445                     // of last center of pattern we saw) to be conservative,
446                     // and also back off by iSkip which is about to be
447                     // re-added
448                     i += rowSkip - stateCount[2] - iSkip;
449                     j = maxJ - 1;
450                   }
451                 }
452               } else {
453                 // Advance to next black pixel
454                 do {
455                   j++;
456                 } while (j < maxJ && !image_->get(j, i));
457                 j--; // back up to that last white pixel
458               }
459               // Clear state to start looking again
460               currentState = 0;
461               stateCount[0] = 0;
462               stateCount[1] = 0;
463               stateCount[2] = 0;
464               stateCount[3] = 0;
465               stateCount[4] = 0;
466             } else { // No, shift counts back by two
467               stateCount[0] = stateCount[2];
468               stateCount[1] = stateCount[3];
469               stateCount[2] = stateCount[4];
470               stateCount[3] = 1;
471               stateCount[4] = 0;
472               currentState = 3;
473             }
474           } else {
475             stateCount[++currentState]++;
476           }
477         } else { // Counting white pixels
478           stateCount[currentState]++;
479         }
480       }
481     }
482     if (foundPatternCross(stateCount)) {
483       bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
484       if (confirmed) {
485         iSkip = stateCount[0];
486         if (hasSkipped_) {
487           // Found a third one
488           done = haveMultiplyConfirmedCenters();
489         }
490       }
491     }
492   }
493
494   vector<Ref<FinderPattern> > patternInfo = selectBestPatterns();
495   patternInfo = orderBestPatterns(patternInfo);
496
497   Ref<FinderPatternInfo> result(new FinderPatternInfo(patternInfo));
498   return result;
499 }
500 }
501 }