Issue 469 -- tweak to special case of all-black 8x8 region. Parse it as black. Other...
[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         int subHeight = height >> 3;
73         int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width);
74
75         matrix = new BitMatrix(width, height);
76         calculateThresholdForBlock(luminances, subWidth, subHeight, width, blackPoints, matrix);
77       } else {
78         // If the image is too small, fall back to the global histogram approach.
79         matrix = super.getBlackMatrix();
80       }
81     }
82   }
83
84   // For each 8x8 block in the image, calculate the average black point using a 5x5 grid
85   // of the blocks around it. Also handles the corner cases, but will ignore up to 7 pixels
86   // on the right edge and 7 pixels at the bottom of the image if the overall dimensions are not
87   // multiples of eight. In practice, leaving those pixels white does not seem to be a problem.
88   private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight,
89       int stride, int[][] blackPoints, BitMatrix matrix) {
90     for (int y = 0; y < subHeight; y++) {
91       for (int x = 0; x < subWidth; x++) {
92         int left = (x > 1) ? x : 2;
93         left = (left < subWidth - 2) ? left : subWidth - 3;
94         int top = (y > 1) ? y : 2;
95         top = (top < subHeight - 2) ? top : subHeight - 3;
96         int sum = 0;
97         for (int z = -2; z <= 2; z++) {
98           int[] blackRow = blackPoints[top + z];
99           sum += blackRow[left - 2];
100           sum += blackRow[left - 1];
101           sum += blackRow[left];
102           sum += blackRow[left + 1];
103           sum += blackRow[left + 2];
104         }
105         int average = sum / 25;
106         threshold8x8Block(luminances, x << 3, y << 3, average, stride, matrix);
107       }
108     }
109   }
110
111   // Applies a single threshold to an 8x8 block of pixels.
112   private static void threshold8x8Block(byte[] luminances, int xoffset, int yoffset, int threshold,
113       int stride, BitMatrix matrix) {
114     for (int y = 0; y < 8; y++) {
115       int offset = (yoffset + y) * stride + xoffset;
116       for (int x = 0; x < 8; x++) {
117         int pixel = luminances[offset + x] & 0xff;
118         if (pixel < threshold) {
119           matrix.set(xoffset + x, yoffset + y);
120         }
121       }
122     }
123   }
124
125   // Calculates a single black point for each 8x8 block of pixels and saves it away.
126   private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight,
127       int stride) {
128     int[][] blackPoints = new int[subHeight][subWidth];
129     for (int y = 0; y < subHeight; y++) {
130       for (int x = 0; x < subWidth; x++) {
131         int sum = 0;
132         int min = 255;
133         int max = 0;
134         for (int yy = 0; yy < 8; yy++) {
135           int offset = ((y << 3) + yy) * stride + (x << 3);
136           for (int xx = 0; xx < 8; xx++) {
137             int pixel = luminances[offset + xx] & 0xff;
138             sum += pixel;
139             if (pixel < min) {
140               min = pixel;
141             }
142             if (pixel > max) {
143               max = pixel;
144             }
145           }
146         }
147
148         // If the contrast is inadequate, use half the minimum, so that this block will be
149         // treated as part of the white background, but won't drag down neighboring blocks
150         // too much.
151         int average;
152         if (max - min > 24) {
153           average = sum >> 6;
154         } else {
155           // When min == max == 0, let average be 1 so all is black
156           average = max == 0 ? 1 : min >> 1;
157         }
158         blackPoints[y][x] = average;
159       }
160     }
161     return blackPoints;
162   }
163
164 }