693f13389b93ad14445926b6cfc6d524b0a7db71
[zxing.git] / cpp / core / src / zxing / common / LocalBlockBinarizer.cpp
1 /*
2  *  LocalBlockBinarizer.cpp
3  *  zxing
4  *
5  *  Created by Ralf Kistner on 17/10/2009.
6  *  Copyright 2008 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 <zxing/common/LocalBlockBinarizer.h>
22
23 namespace zxing {
24
25 const int GLOBAL = 0;
26 const int THRESHOLD = 1;
27
28 LocalBlockBinarizer::LocalBlockBinarizer(Ref<LuminanceSource> source) :
29     Binarizer(source) {
30
31 }
32
33 LocalBlockBinarizer::~LocalBlockBinarizer() {
34 }
35
36 // Calculates the final BitMatrix once for all requests. This could be called once from the
37 // constructor instead, but there are some advantages to doing it lazily, such as making
38 // profiling easier, and not doing heavy lifting when callers don't expect it.
39 Ref<BitMatrix> LocalBlockBinarizer::estimateBlackMatrix() {
40   Ref<LuminanceSource> source = getSource();
41   unsigned char* luminances = source->copyMatrix();
42   int width = source->getWidth();
43   int height = source->getHeight();
44   // Sharpening does not really help for 2d barcodes
45   //    sharpenRow(luminances, width, height);
46
47   int subWidth = width >> 3;
48   int subHeight = height >> 3;
49
50   unsigned char* averages = new unsigned char[subWidth * subHeight];
51   unsigned char* types = new unsigned char[subWidth * subHeight];
52
53   calculateBlackPoints(luminances, averages, types, subWidth, subHeight, width);
54
55   Ref<BitMatrix> matrix(new BitMatrix(width, height));
56   calculateThresholdForBlock(luminances, subWidth, subHeight, width, averages, types, *matrix);
57
58   delete[] averages;
59   delete[] types;
60   delete[] luminances;
61
62   return matrix;
63 }
64
65 // For each 8x8 block in the image, calculate the average black point using a 5x5 grid
66 // of the blocks around it. Also handles the corner cases, but will ignore up to 7 pixels
67 // on the right edge and 7 pixels at the bottom of the image if the overall dimensions are not
68 // multiples of eight. In practice, leaving those pixels white does not seem to be a problem.
69 void LocalBlockBinarizer::calculateThresholdForBlock(const unsigned char* luminances, int subWidth, int subHeight,
70     int stride, const unsigned char* averages, const unsigned char* types, BitMatrix& matrix) {
71   // Calculate global average
72   int global = 0;
73   for (int y = 0; y < subHeight; y++) {
74     for (int x = 0; x < subWidth; x++) {
75       global += averages[y * subWidth + x];
76     }
77   }
78
79   global /= subWidth * subHeight;
80
81
82   for (int y = 0; y < subHeight; y++) {
83     for (int x = 0; x < subWidth; x++) {
84       int left = (x > 0) ? x : 1;
85       left = (left < subWidth - 1) ? left : subWidth - 2;
86       int top = (y > 0) ? y : 1;
87       top = (top < subHeight - 1) ? top : subHeight - 2;
88       int sum = 0;
89       int contrast = 0;
90       for (int z = -1; z <= 1; z++) {
91 //                              sum += averages[(top + z) * subWidth + left - 2];
92         sum += averages[(top + z) * subWidth + left - 1];
93         sum += averages[(top + z) * subWidth + left];
94         sum += averages[(top + z) * subWidth + left + 1];
95 //                              sum += averages[(top + z) * subWidth + left + 2];
96
97 //                              type += types[(top + z) * subWidth + left - 2];
98         contrast += types[(top + z) * subWidth + left - 1];
99         contrast += types[(top + z) * subWidth + left];
100         contrast += types[(top + z) * subWidth + left + 1];
101 //                              type += types[(top + z) * subWidth + left + 2];
102       }
103       int average = sum / 9;
104
105
106       if (contrast > 2)
107         threshold8x8Block(luminances, x << 3, y << 3, average, stride, matrix);
108 //                      else if(average < global)       // Black
109 //                              matrix.setRegion(x << 3, y << 3, 8, 8);
110       // If white, we don't need to do anything - the block is already cleared.
111     }
112   }
113 }
114
115 // Applies a single threshold to an 8x8 block of pixels.
116 void LocalBlockBinarizer::threshold8x8Block(const unsigned char* luminances, int xoffset, int yoffset, int threshold,
117     int stride, BitMatrix& matrix) {
118   for (int y = 0; y < 8; y++) {
119     int offset = (yoffset + y) * stride + xoffset;
120     for (int x = 0; x < 8; x++) {
121       int pixel = luminances[offset + x];
122       if (pixel < threshold) {
123         matrix.set(xoffset + x, yoffset + y);
124       }
125     }
126   }
127 }
128
129 // Calculates a single black point for each 8x8 block of pixels and saves it away.
130 void LocalBlockBinarizer::calculateBlackPoints(const unsigned char* luminances, unsigned char* averages,
131     unsigned char* types, int subWidth, int subHeight, int stride) {
132   for (int y = 0; y < subHeight; y++) {
133     for (int x = 0; x < subWidth; x++) {
134       int sum = 0;
135       int min = 255;
136       int max = 0;
137       for (int yy = 0; yy < 8; yy++) {
138         int offset = ((y << 3) + yy) * stride + (x << 3);
139         const unsigned char* lumo = luminances + offset;
140         for (int xx = 0; xx < 8; xx++) {
141           int pixel = lumo[xx];
142           sum += pixel;
143           if (pixel < min) {
144             min = pixel;
145           }
146           if (pixel > max) {
147             max = pixel;
148           }
149         }
150       }
151
152       // If the contrast is inadequate, we treat the block as white.
153       // An arbitrary value is chosen here. Higher values mean less noise, but may also reduce
154       // the ability to recognise some barcodes.
155       int average = sum >> 6;
156       int type;
157
158       if (max - min > 30)
159         type = THRESHOLD;
160       else
161         type = GLOBAL;
162       //                        int average = (max - min > 24) ? (sum >> 6) : (min-1);
163       averages[y * subWidth + x] = average;
164       types[y * subWidth + x] = type;
165     }
166   }
167 }
168
169 // Applies a simple -1 4 -1 box filter with a weight of 2 to each row.
170 void LocalBlockBinarizer::sharpenRow(unsigned char* luminances, int width, int height) {
171   for (int y = 0; y < height; y++) {
172     int offset = y * width;
173     int left = luminances[offset];
174     int center = luminances[offset + 1];
175     for (int x = 1; x < width - 1; x++) {
176       unsigned char right = luminances[offset + x + 1];
177       int pixel = ((center << 2) - left - right) >> 1;
178       // Must clamp values to 0..255 so they will fit in a byte.
179       if (pixel > 255) {
180         pixel = 255;
181       } else if (pixel < 0) {
182         pixel = 0;
183       }
184       luminances[offset + x] = (unsigned char)pixel;
185       left = center;
186       center = right;
187     }
188   }
189 }
190
191 }