Fix bad logic black point estimator, improving threshold estimation performance ...
[zxing.git] / javase / src / com / google / zxing / client / j2se / BufferedImageMonochromeBitmapSource.java
1 /*
2  * Copyright 2007 Google Inc.
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.client.j2se;
18
19 import com.google.zxing.BlackPointEstimationMethod;
20 import com.google.zxing.MonochromeBitmapSource;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.common.BitArray;
23 import com.google.zxing.common.BlackPointEstimator;
24
25 import java.awt.geom.AffineTransform;
26 import java.awt.image.AffineTransformOp;
27 import java.awt.image.BufferedImage;
28 import java.awt.image.BufferedImageOp;
29
30 /**
31  * <p>An implementation based upon {@link BufferedImage}. This provides access to the
32  * underlying image as if it were a monochrome image. Behind the scenes, it is evaluating
33  * the luminance of the underlying image by retrieving its pixels' RGB values.</p>
34  *
35  * <p>This may also be used to construct a {@link MonochromeBitmapSource}
36  * based on a region of a {@link BufferedImage}; see
37  * {@link #BufferedImageMonochromeBitmapSource(BufferedImage, int, int, int, int)}.</p>
38  *
39  * @author srowen@google.com (Sean Owen), Daniel Switkin (dswitkin@google.com)
40  */
41 public final class BufferedImageMonochromeBitmapSource implements MonochromeBitmapSource {
42
43   private final BufferedImage image;
44   private final int left;
45   private final int top;
46   private final int width;
47   private final int height;
48   private int blackPoint;
49   private BlackPointEstimationMethod lastMethod;
50   private int lastArgument;
51
52   private static final int LUMINANCE_BITS = 5;
53   private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
54   private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
55
56   /**
57    * Creates an instance that uses the entire given image as a source of pixels to decode.
58    *
59    * @param image image to decode
60    */
61   public BufferedImageMonochromeBitmapSource(BufferedImage image) {
62     this(image, 0, 0, image.getWidth(), image.getHeight());
63   }
64
65   /**
66    * Creates an instance that uses only a region of the given image as a source of pixels to decode.
67    *
68    * @param image image to decode a region of
69    * @param left x coordinate of leftmost pixels to decode
70    * @param top y coordinate of topmost pixels to decode
71    * @param right one more than the x coordinate of rightmost pixels to decode. That is, we will decode
72    *  pixels whose x coordinate is in [left,right)
73    * @param bottom likewise, one more than the y coordinate of the bottommost pixels to decode
74    */
75   public BufferedImageMonochromeBitmapSource(BufferedImage image, int left, int top, int right, int bottom) {
76     this.image = image;
77     blackPoint = 0x7F;
78     lastMethod = null;
79     lastArgument = 0;
80     int sourceHeight = image.getHeight();
81     int sourceWidth = image.getWidth();
82     if (left < 0 || top < 0 || right > sourceWidth || bottom > sourceHeight || right <= left || bottom <= top) {
83       throw new IllegalArgumentException("Invalid bounds: (" + top + ',' + left + ") (" + right + ',' + bottom + ')');
84     }
85     this.left = left;
86     this.top = top;
87     this.width = right - left;
88     this.height = bottom - top;
89   }
90
91   /**
92    * @return underlying {@link BufferedImage} behind this instance. Note that even if this instance
93    *  only uses a subset of the full image, the returned value here represents the entire backing image.
94    */
95   public BufferedImage getImage() {
96     return image;
97   }
98
99   private int getRGB(int x, int y) {
100     return image.getRGB(left + x, top + y);
101   }
102
103   private void getRGBRow(int startX, int startY, int[] result) {
104     image.getRGB(left + startX, top + startY, result.length, 1, result, 0, result.length);
105   }
106
107   public boolean isBlack(int x, int y) {
108     return computeRGBLuminance(getRGB(x, y)) < blackPoint;
109   }
110
111   public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) {
112     if (row == null || row.getSize() < getWidth) {
113       row = new BitArray(getWidth);
114     } else {
115       row.clear();
116     }
117     int[] pixelRow = new int[getWidth];
118     getRGBRow(startX, y, pixelRow);
119
120     // If the current decoder calculated the blackPoint based on one row, assume we're trying to
121     // decode a 1D barcode, and apply some sharpening.
122     // TODO: We may want to add a fifth parameter to request the amount of shapening to be done.
123     if (lastMethod.equals(BlackPointEstimationMethod.ROW_SAMPLING)) {
124       int left = computeRGBLuminance(pixelRow[0]);
125       int center = computeRGBLuminance(pixelRow[1]);
126       for (int i = 1; i < getWidth - 1; i++) {
127         int right = computeRGBLuminance(pixelRow[i + 1]);
128         // Simple -1 4 -1 box filter with a weight of 2
129         int luminance = ((center << 2) - left - right) >> 1;
130         if (luminance < blackPoint) {
131           row.set(i);
132         }
133         left = center;
134         center = right;
135       }
136     } else {
137       for (int i = 0; i < getWidth; i++) {
138         if (computeRGBLuminance(pixelRow[i]) < blackPoint) {
139           row.set(i);
140         }
141       }
142     }
143     return row;
144   }
145
146   public int getHeight() {
147     return height;
148   }
149
150   public int getWidth() {
151     return width;
152   }
153
154   public void estimateBlackPoint(BlackPointEstimationMethod method, int argument) throws ReaderException {
155     if (!method.equals(lastMethod) || argument != lastArgument) {
156       int[] histogram = new int[LUMINANCE_BUCKETS];
157       if (method.equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) {
158         int minDimension = width < height ? width : height;
159         int startI = height == minDimension ? 0 : (height - width) >> 1;
160         int startJ = width == minDimension ? 0 : (width - height) >> 1;
161         for (int n = 0; n < minDimension; n++) {
162           int pixel = getRGB(startJ + n, startI + n);
163           histogram[computeRGBLuminance(pixel) >> LUMINANCE_SHIFT]++;
164         }
165       } else if (method.equals(BlackPointEstimationMethod.ROW_SAMPLING)) {
166         if (argument < 0 || argument >= height) {
167           throw new IllegalArgumentException("Row is not within the image: " + argument);
168         }
169         int[] rgbArray = new int[width];
170         getRGBRow(0, argument, rgbArray);
171         for (int x = 0; x < width; x++) {
172           histogram[computeRGBLuminance(rgbArray[x]) >> LUMINANCE_SHIFT]++;
173         }
174       } else {
175         throw new IllegalArgumentException("Unknown method: " + method);
176       }
177       blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT;
178       lastMethod = method;
179       lastArgument = argument;
180     }
181   }
182
183   public BlackPointEstimationMethod getLastEstimationMethod() {
184     return lastMethod;
185   }
186
187   public MonochromeBitmapSource rotateCounterClockwise() {
188     if (!isRotateSupported()) {
189       throw new IllegalStateException("Rotate not supported");
190     }
191     int sourceWidth = image.getWidth();
192     int sourceHeight = image.getHeight();
193     // 90 degrees counterclockwise:
194     AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
195     BufferedImageOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
196     // Note width/height are flipped since we are rotating 90 degrees:
197     BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, image.getType());
198     op.filter(image, rotatedImage);
199     return new BufferedImageMonochromeBitmapSource(rotatedImage,
200                                                    top,
201                                                    sourceWidth - (left + width),
202                                                    top + height,
203                                                    sourceWidth - left);
204   }
205
206   public boolean isRotateSupported() {
207     // Can't run AffineTransforms on images of unknown format
208     return image.getType() != BufferedImage.TYPE_CUSTOM;
209   }
210
211   /**
212    * Extracts luminance from a pixel from this source. By default, the source is assumed to use RGB,
213    * so this implementation computes luminance is a function of a red, green and blue components as
214    * follows:
215    *
216    * <code>Y = 0.299R + 0.587G + 0.114B</code>
217    *
218    * where R, G, and B are values in [0,1].
219    */
220   private static int computeRGBLuminance(int pixel) {
221     // Coefficients add up to 1024 to make the divide into a fast shift
222     return (306 * ((pixel >> 16) & 0xFF) +
223         601 * ((pixel >> 8) & 0xFF) +
224         117 * (pixel & 0xFF)) >> 10;
225   }
226
227 }