C++ port: add decode hints system
[zxing.git] / cpp / core / src / zxing / oned / OneDReader.cpp
1 /*
2  *  OneDReader.cpp
3  *  ZXing
4  *
5  *  Created by Lukasz Warchol on 10-01-15.
6  *  Copyright 2010 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 "OneDReader.h"
22 #include <zxing/ReaderException.h>
23 #include <zxing/oned/OneDResultPoint.h>
24 #include <math.h>
25 #include <limits.h>
26
27 namespace zxing {
28         namespace oned {
29                 using namespace std;
30                 
31                 OneDReader::OneDReader() {
32                 }
33                 
34                 Ref<Result> OneDReader::decode(Ref<BinaryBitmap> image, DecodeHints hints) {
35
36                   try {
37                                 return doDecode(image, hints);
38                         }catch (ReaderException re) {
39                                 if (hints.getTryHarder() && image->isRotateSupported()) {
40
41                                         Ref<BinaryBitmap> rotatedImage(image->rotateCounterClockwise());
42                                         Ref<Result> result(doDecode(rotatedImage, hints));
43                                         /*
44                                         // Record that we found it rotated 90 degrees CCW / 270 degrees CW
45                                         Hashtable metadata = result.getResultMetadata();
46                                         int orientation = 270;
47                                         if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
48                                                 // But if we found it reversed in doDecode(), add in that result here:
49                                                 orientation = (orientation +
50                                                                            ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
51                                         }
52                                         result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
53                                         */
54           // Update result points
55                                         std::vector<Ref<ResultPoint> > points (result->getResultPoints());
56                                         int height = rotatedImage->getHeight();
57                                         for (size_t i = 0; i < points.size(); i++) {
58                                                 points[i].reset(new OneDResultPoint(height - points[i]->getY() - 1, points[i]->getX()));
59                                         }
60                                         return result;
61                                 } else {
62                                         throw re;
63                                 }
64                         }
65                 }
66                 
67                 Ref<Result> OneDReader::doDecode(Ref<BinaryBitmap> image, DecodeHints hints){
68                         int width = image->getWidth();
69                         int height = image->getHeight();
70                         Ref<BitArray> row(new BitArray(width));
71                         int middle = height >> 1;
72                         bool tryHarder = hints.getTryHarder();
73                         int rowStep = (int)fmax(1, height >> (tryHarder ? 8 : 5));
74                         int maxLines;
75                         if (tryHarder) {
76                                 maxLines = height; // Look at the whole image, not just the center
77                         } else {
78         maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
79                         }
80                         
81                         for (int x = 0; x < maxLines; x++) {
82                                 
83                                 // Scanning from the middle out. Determine which row we're looking at next:
84                                 int rowStepsAboveOrBelow = (x + 1) >> 1;
85                                 bool isAbove = (x & 0x01) == 0; // i.e. is x even?
86                                 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
87                                 if (rowNumber < 0 || rowNumber >= height) {
88                                         // Oops, if we run off the top or bottom, stop
89                                         break;
90                                 }
91                                         
92                                 // Estimate black point for this row and load it:
93                                 try {
94                                         row = image->getBlackRow(rowNumber, row);
95                                 }catch (ReaderException re) {
96                                         continue;
97                                 }catch (IllegalArgumentException re) {
98           continue;
99                                 }
100                                 
101                                 // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
102                                 // handle decoding upside down barcodes.
103                                 for (int attempt = 0; attempt < 2; attempt++) {
104                                         if (attempt == 1) { // trying again?
105                                                 row->reverse(); // reverse the row and continue
106                                         }
107                                         try {
108                                                 // Look for a barcode
109                                                 Ref<Result> result = decodeRow(rowNumber, row);
110                                                 // We found our barcode
111                                                 if (attempt == 1) {
112                                                         //                                              // But it was upside down, so note that
113                                                         //                                              result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
114                                                         //                                              // And remember to flip the result points horizontally.
115                                                   std::vector<Ref<ResultPoint> > points(result->getResultPoints());
116                                                   // if there's exactly two points (which there should be), flip the x coordinate
117               // if there's not exactly 2, I don't know what do do with it
118                                                   if (points.size() == 2) {
119                 Ref<ResultPoint> pointZero(new OneDResultPoint(width - points[0]->getX() - 1, points[0]->getY()));
120                 points[0] = pointZero;
121
122                 Ref<ResultPoint> pointOne(new OneDResultPoint(width - points[1]->getX() - 1, points[1]->getY()));
123                 points[1] = pointOne;
124
125                 result.reset(new Result(result->getText(),result->getRawBytes(),points,result->getBarcodeFormat()));
126                                                   }
127                                                 }
128                                                 return result;
129                                         } catch (ReaderException re) {
130                                                 // continue -- just couldn't decode this row
131                                         }
132                                 }
133                         }
134                         throw ReaderException("doDecode() failed");
135                 }
136                 
137                 unsigned int OneDReader::patternMatchVariance(int counters[], int countersSize, const int pattern[], int maxIndividualVariance) {
138                         int numCounters = countersSize;
139                         unsigned int total = 0;
140                         unsigned int patternLength = 0;
141                         for (int i = 0; i < numCounters; i++) {
142                                 total += counters[i];
143                                 patternLength += pattern[i];
144                         }
145                         if (total < patternLength) {
146                                 // If we don't even have one pixel per unit of bar width, assume this is too small
147                                 // to reliably match, so fail:
148                                 return INT_MAX;
149                         }
150                         // We're going to fake floating-point math in integers. We just need to use more bits.
151                         // Scale up patternLength so that intermediate values below like scaledCounter will have
152                         // more "significant digits"
153                         unsigned int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
154                         maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
155                         
156                         unsigned int totalVariance = 0;
157                         for (int x = 0; x < numCounters; x++) {
158                                 int counter = counters[x] << INTEGER_MATH_SHIFT;
159                                 int scaledPattern = pattern[x] * unitBarWidth;
160                                 int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
161                                 if (variance > maxIndividualVariance) {
162                                         return INT_MAX;
163                                 }
164                                 totalVariance += variance;
165                         }
166                         return totalVariance / total;
167                 }
168                 
169                 void OneDReader::recordPattern(Ref<BitArray> row, int start, int counters[], int countersCount){
170                         int numCounters = countersCount;//sizeof(counters) / sizeof(int);
171                         for (int i = 0; i < numCounters; i++) {
172                                 counters[i] = 0;
173                         }
174                         int end = row->getSize();
175                         if (start >= end) {
176                                 throw ReaderException("recordPattern: start >= end");
177                         }
178                         bool isWhite = !row->get(start);
179                         int counterPosition = 0;
180                         int i = start;
181                         while (i < end) {
182                                 bool pixel = row->get(i);
183                                 if (pixel ^ isWhite) { // that is, exactly one is true
184                                         counters[counterPosition]++;
185                                 } else {
186                                         counterPosition++;
187                                         if (counterPosition == numCounters) {
188                                                 break;
189                                         } else {
190                                                 counters[counterPosition] = 1;
191                                                 isWhite ^= true; // isWhite = !isWhite;
192                                         }
193                                 }
194                                 i++;
195                         }
196                         // If we read fully the last section of pixels and filled up our counters -- or filled
197                         // the last counter but ran off the side of the image, OK. Otherwise, a problem.
198                         if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
199                                 throw ReaderException("recordPattern");
200                         }
201                 }
202                 
203                 OneDReader::~OneDReader() {
204                 }
205         }
206 }