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