Finished work on the local binarizer and renamed it to HybridBinarizer. It uses the...
[zxing.git] / core / src / com / google / zxing / common / GlobalHistogramBinarizer.java
1 /*
2  * Copyright 2009 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
17 package com.google.zxing.common;
18
19 import com.google.zxing.Binarizer;
20 import com.google.zxing.LuminanceSource;
21 import com.google.zxing.ReaderException;
22
23 /**
24  * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
25  * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
26  * algorithm. However, because it picks a global black point, it cannot handle difficult shadows
27  * and gradients.
28  *
29  * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
30  *
31  * @author dswitkin@google.com (Daniel Switkin)
32  * @author Sean Owen
33  */
34 public class GlobalHistogramBinarizer extends Binarizer {
35
36   private static final int LUMINANCE_BITS = 5;
37   private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
38   private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
39
40   private byte[] luminances = null;
41   private int[] buckets = null;
42
43   public GlobalHistogramBinarizer(LuminanceSource source) {
44     super(source);
45   }
46
47   // Applies simple sharpening to the row data to improve performance of the 1D Readers.
48   public BitArray getBlackRow(int y, BitArray row) throws ReaderException {
49     LuminanceSource source = getLuminanceSource();
50     int width = source.getWidth();
51     if (row == null || row.getSize() < width) {
52       row = new BitArray(width);
53     } else {
54       row.clear();
55     }
56
57     initArrays(width);
58     byte[] localLuminances = source.getRow(y, luminances);
59     int[] localBuckets = buckets;
60     for (int x = 0; x < width; x++) {
61       int pixel = localLuminances[x] & 0xff;
62       localBuckets[pixel >> LUMINANCE_SHIFT]++;
63     }
64     int blackPoint = estimateBlackPoint(localBuckets);
65
66     int left = localLuminances[0] & 0xff;
67     int center = localLuminances[1] & 0xff;
68     for (int x = 1; x < width - 1; x++) {
69       int right = localLuminances[x + 1] & 0xff;
70       // A simple -1 4 -1 box filter with a weight of 2.
71       int luminance = ((center << 2) - left - right) >> 1;
72       if (luminance < blackPoint) {
73         row.set(x);
74       }
75       left = center;
76       center = right;
77     }
78     return row;
79   }
80
81   // Does not sharpen the data, as this call is intended to only be used by 2D Readers.
82   public BitMatrix getBlackMatrix() throws ReaderException {
83     LuminanceSource source = getLuminanceSource();
84     int width = source.getWidth();
85     int height = source.getHeight();
86     BitMatrix matrix = new BitMatrix(width, height);
87
88     // Quickly calculates the histogram by sampling four rows from the image. This proved to be
89     // more robust on the blackbox tests than sampling a diagonal as we used to do.
90     initArrays(width);
91     int[] localBuckets = buckets;
92     for (int y = 1; y < 5; y++) {
93       int row = height * y / 5;
94       byte[] localLuminances = source.getRow(row, luminances);
95       int right = (width << 2) / 5;
96       for (int x = width / 5; x < right; x++) {
97         int pixel = localLuminances[x] & 0xff;
98         localBuckets[pixel >> LUMINANCE_SHIFT]++;
99       }
100     }
101     int blackPoint = estimateBlackPoint(localBuckets);
102
103     // We delay reading the entire image luminance until the black point estimation succeeds.
104     // Although we end up reading four rows twice, it is consistent with our motto of
105     // "fail quickly" which is necessary for continuous scanning.
106     byte[] localLuminances = source.getMatrix();
107     for (int y = 0; y < height; y++) {
108       int offset = y * width;
109       for (int x = 0; x< width; x++) {
110         int pixel = localLuminances[offset + x] & 0xff;
111         if (pixel < blackPoint) {
112           matrix.set(x, y);
113         }
114       }
115     }
116
117     return matrix;
118   }
119
120   public Binarizer createBinarizer(LuminanceSource source) {
121     return new GlobalHistogramBinarizer(source);
122   }
123
124   private void initArrays(int luminanceSize) {
125     if (luminances == null || luminances.length < luminanceSize) {
126       luminances = new byte[luminanceSize];
127     }
128     if (buckets == null) {
129       buckets = new int[LUMINANCE_BUCKETS];
130     } else {
131       for (int x = 0; x < LUMINANCE_BUCKETS; x++) {
132         buckets[x] = 0;
133       }
134     }
135   }
136
137   private static int estimateBlackPoint(int[] buckets) throws ReaderException {
138     // Find the tallest peak in the histogram.
139     int numBuckets = buckets.length;
140     int maxBucketCount = 0;
141     int firstPeak = 0;
142     int firstPeakSize = 0;
143     for (int x = 0; x < numBuckets; x++) {
144       if (buckets[x] > firstPeakSize) {
145         firstPeak = x;
146         firstPeakSize = buckets[x];
147       }
148       if (buckets[x] > maxBucketCount) {
149         maxBucketCount = buckets[x];
150       }
151     }
152
153     // Find the second-tallest peak which is somewhat far from the tallest peak.
154     int secondPeak = 0;
155     int secondPeakScore = 0;
156     for (int x = 0; x < numBuckets; x++) {
157       int distanceToBiggest = x - firstPeak;
158       // Encourage more distant second peaks by multiplying by square of distance.
159       int score = buckets[x] * distanceToBiggest * distanceToBiggest;
160       if (score > secondPeakScore) {
161         secondPeak = x;
162         secondPeakScore = score;
163       }
164     }
165
166     // Make sure firstPeak corresponds to the black peak.
167     if (firstPeak > secondPeak) {
168       int temp = firstPeak;
169       firstPeak = secondPeak;
170       secondPeak = temp;
171     }
172
173     // If there is too little contrast in the image to pick a meaningful black point, throw rather
174     // than waste time trying to decode the image, and risk false positives.
175     // TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the
176     // two peaks, to determine the contrast.
177     if (secondPeak - firstPeak <= numBuckets >> 4) {
178       throw ReaderException.getInstance();
179     }
180
181     // Find a valley between them that is low and closer to the white peak.
182     int bestValley = secondPeak - 1;
183     int bestValleyScore = -1;
184     for (int x = secondPeak - 1; x > firstPeak; x--) {
185       int fromFirst = x - firstPeak;
186       int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
187       if (score > bestValleyScore) {
188         bestValley = x;
189         bestValleyScore = score;
190       }
191     }
192
193     return bestValley << LUMINANCE_SHIFT;
194   }
195
196 }