Issue 508
[zxing.git] / core / src / com / google / zxing / common / HybridBinarizer.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.NotFoundException;
22
23 /**
24  * This class implements a local thresholding algorithm, which while slower than the
25  * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
26  * high frequency images of barcodes with black data on white backgrounds. For this application,
27  * it does a much better job than a global blackpoint with severe shadows and gradients.
28  * However it tends to produce artifacts on lower frequency images and is therefore not
29  * a good general purpose binarizer for uses outside ZXing.
30  *
31  * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
32  * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
33  * inherently local, and only fails for horizontal gradients. We can revisit that problem later,
34  * but for now it was not a win to use local blocks for 1D.
35  *
36  * This Binarizer is the default for the unit tests and the recommended class for library users.
37  *
38  * @author dswitkin@google.com (Daniel Switkin)
39  */
40 public final class HybridBinarizer extends GlobalHistogramBinarizer {
41
42   // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
43   // So this is the smallest dimension in each axis we can accept.
44   private static final int MINIMUM_DIMENSION = 40;
45
46   private BitMatrix matrix = null;
47
48   public HybridBinarizer(LuminanceSource source) {
49     super(source);
50   }
51
52   public BitMatrix getBlackMatrix() throws NotFoundException {
53     binarizeEntireImage();
54     return matrix;
55   }
56
57   public Binarizer createBinarizer(LuminanceSource source) {
58     return new HybridBinarizer(source);
59   }
60
61   // Calculates the final BitMatrix once for all requests. This could be called once from the
62   // constructor instead, but there are some advantages to doing it lazily, such as making
63   // profiling easier, and not doing heavy lifting when callers don't expect it.
64   private void binarizeEntireImage() throws NotFoundException {
65     if (matrix == null) {
66       LuminanceSource source = getLuminanceSource();
67       if (source.getWidth() >= MINIMUM_DIMENSION && source.getHeight() >= MINIMUM_DIMENSION) {
68         byte[] luminances = source.getMatrix();
69         int width = source.getWidth();
70         int height = source.getHeight();
71         int subWidth = width >> 3;
72         if ((width & 0x07) != 0) {
73           subWidth++;
74         }
75         int subHeight = height >> 3;
76         if ((height & 0x07) != 0) {
77           subHeight++;
78         }
79         int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height);
80
81         matrix = new BitMatrix(width, height);
82         calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, matrix);
83       } else {
84         // If the image is too small, fall back to the global histogram approach.
85         matrix = super.getBlackMatrix();
86       }
87     }
88   }
89
90   // For each 8x8 block in the image, calculate the average black point using a 5x5 grid
91   // of the blocks around it. Also handles the corner cases (fractional blocks are computed based
92   // on the last 8 pixels in the row/column which are also used in the previous block).
93   private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight,
94       int width, int height, int[][] blackPoints, BitMatrix matrix) {
95     for (int y = 0; y < subHeight; y++) {
96       int yoffset = y << 3;
97       if ((yoffset + 8) >= height) {
98         yoffset = height - 8;
99       }
100       for (int x = 0; x < subWidth; x++) {
101         int xoffset = x << 3;
102         if ((xoffset + 8) >= width) {
103             xoffset = width - 8;
104         }
105         int left = (x > 1) ? x : 2;
106         left = (left < subWidth - 2) ? left : subWidth - 3;
107         int top = (y > 1) ? y : 2;
108         top = (top < subHeight - 2) ? top : subHeight - 3;
109         int sum = 0;
110         for (int z = -2; z <= 2; z++) {
111           int[] blackRow = blackPoints[top + z];
112           sum += blackRow[left - 2];
113           sum += blackRow[left - 1];
114           sum += blackRow[left];
115           sum += blackRow[left + 1];
116           sum += blackRow[left + 2];
117         }
118         int average = sum / 25;
119         threshold8x8Block(luminances, xoffset, yoffset, average, width, matrix);
120       }
121     }
122   }
123
124   // Applies a single threshold to an 8x8 block of pixels.
125   private static void threshold8x8Block(byte[] luminances, int xoffset, int yoffset, int threshold,
126       int stride, BitMatrix matrix) {
127     for (int y = 0; y < 8; y++) {
128       int offset = (yoffset + y) * stride + xoffset;
129       for (int x = 0; x < 8; x++) {
130         int pixel = luminances[offset + x] & 0xff;
131         if (pixel < threshold) {
132           matrix.set(xoffset + x, yoffset + y);
133         }
134       }
135     }
136   }
137
138   // Calculates a single black point for each 8x8 block of pixels and saves it away.
139   private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight,
140       int width, int height) {
141     int[][] blackPoints = new int[subHeight][subWidth];
142     for (int y = 0; y < subHeight; y++) {
143       int yoffset = y << 3;
144       if ((yoffset + 8) >= height) {
145         yoffset = height - 8;
146       }
147       for (int x = 0; x < subWidth; x++) {
148         int xoffset = x << 3;
149         if ((xoffset + 8) >= width) {
150             xoffset = width - 8;
151         }
152         int sum = 0;
153         int min = 255;
154         int max = 0;
155         for (int yy = 0; yy < 8; yy++) {
156           int offset = (yoffset + yy) * width + xoffset;
157           for (int xx = 0; xx < 8; xx++) {
158             int pixel = luminances[offset + xx] & 0xff;
159             sum += pixel;
160             if (pixel < min) {
161               min = pixel;
162             }
163             if (pixel > max) {
164               max = pixel;
165             }
166           }
167         }
168
169         // If the contrast is inadequate, use half the minimum, so that this block will be
170         // treated as part of the white background, but won't drag down neighboring blocks
171         // too much.
172         int average;
173         if (max - min > 24) {
174           average = sum >> 6;
175         } else {
176           // When min == max == 0, let average be 1 so all is black
177           average = max == 0 ? 1 : min >> 1;
178         }
179         blackPoints[y][x] = average;
180       }
181     }
182     return blackPoints;
183   }
184
185 }