Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ZXHybridBinarizer.m 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /*
  2. * Copyright 2012 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. #import "ZXByteArray.h"
  17. #import "ZXHybridBinarizer.h"
  18. #import "ZXIntArray.h"
  19. // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
  20. // So this is the smallest dimension in each axis we can accept.
  21. const int ZX_BLOCK_SIZE_POWER = 3;
  22. const int ZX_BLOCK_SIZE = 1 << ZX_BLOCK_SIZE_POWER; // ...0100...00
  23. const int ZX_BLOCK_SIZE_MASK = ZX_BLOCK_SIZE - 1; // ...0011...11
  24. const int ZX_MINIMUM_DIMENSION = ZX_BLOCK_SIZE * 5;
  25. const int ZX_MIN_DYNAMIC_RANGE = 24;
  26. @interface ZXHybridBinarizer ()
  27. @property (nonatomic, strong) ZXBitMatrix *matrix;
  28. @end
  29. @implementation ZXHybridBinarizer
  30. /**
  31. * Calculates the final BitMatrix once for all requests. This could be called once from the
  32. * constructor instead, but there are some advantages to doing it lazily, such as making
  33. * profiling easier, and not doing heavy lifting when callers don't expect it.
  34. */
  35. - (ZXBitMatrix *)blackMatrixWithError:(NSError **)error {
  36. if (self.matrix != nil) {
  37. return self.matrix;
  38. }
  39. ZXLuminanceSource *source = [self luminanceSource];
  40. int width = source.width;
  41. int height = source.height;
  42. if (width >= ZX_MINIMUM_DIMENSION && height >= ZX_MINIMUM_DIMENSION) {
  43. ZXByteArray *luminances = source.matrix;
  44. int subWidth = width >> ZX_BLOCK_SIZE_POWER;
  45. if ((width & ZX_BLOCK_SIZE_MASK) != 0) {
  46. subWidth++;
  47. }
  48. int subHeight = height >> ZX_BLOCK_SIZE_POWER;
  49. if ((height & ZX_BLOCK_SIZE_MASK) != 0) {
  50. subHeight++;
  51. }
  52. int **blackPoints = [self calculateBlackPoints:luminances.array subWidth:subWidth subHeight:subHeight width:width height:height];
  53. ZXBitMatrix *newMatrix = [[ZXBitMatrix alloc] initWithWidth:width height:height];
  54. [self calculateThresholdForBlock:luminances.array subWidth:subWidth subHeight:subHeight width:width height:height blackPoints:blackPoints matrix:newMatrix];
  55. self.matrix = newMatrix;
  56. for (int i = 0; i < subHeight; i++) {
  57. free(blackPoints[i]);
  58. }
  59. free(blackPoints);
  60. } else {
  61. // If the image is too small, fall back to the global histogram approach.
  62. self.matrix = [super blackMatrixWithError:error];
  63. }
  64. return self.matrix;
  65. }
  66. - (ZXBinarizer *)createBinarizer:(ZXLuminanceSource *)source {
  67. return [[ZXHybridBinarizer alloc] initWithSource:source];
  68. }
  69. /**
  70. * For each block in the image, calculate the average black point using a 5x5 grid
  71. * of the blocks around it. Also handles the corner cases (fractional blocks are computed based
  72. * on the last pixels in the row/column which are also used in the previous block).
  73. */
  74. - (void)calculateThresholdForBlock:(int8_t *)luminances
  75. subWidth:(int)subWidth
  76. subHeight:(int)subHeight
  77. width:(int)width
  78. height:(int)height
  79. blackPoints:(int **)blackPoints
  80. matrix:(ZXBitMatrix *)matrix {
  81. for (int y = 0; y < subHeight; y++) {
  82. int yoffset = y << ZX_BLOCK_SIZE_POWER;
  83. int maxYOffset = height - ZX_BLOCK_SIZE;
  84. if (yoffset > maxYOffset) {
  85. yoffset = maxYOffset;
  86. }
  87. for (int x = 0; x < subWidth; x++) {
  88. int xoffset = x << ZX_BLOCK_SIZE_POWER;
  89. int maxXOffset = width - ZX_BLOCK_SIZE;
  90. if (xoffset > maxXOffset) {
  91. xoffset = maxXOffset;
  92. }
  93. int left = [self cap:x min:2 max:subWidth - 3];
  94. int top = [self cap:y min:2 max:subHeight - 3];
  95. int sum = 0;
  96. for (int z = -2; z <= 2; z++) {
  97. int *blackRow = blackPoints[top + z];
  98. sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2];
  99. }
  100. int average = sum / 25;
  101. [self thresholdBlock:luminances xoffset:xoffset yoffset:yoffset threshold:average stride:width matrix:matrix];
  102. }
  103. }
  104. }
  105. - (int)cap:(int)value min:(int)min max:(int)max {
  106. return value < min ? min : value > max ? max : value;
  107. }
  108. /**
  109. * Applies a single threshold to a block of pixels.
  110. */
  111. - (void)thresholdBlock:(int8_t *)luminances
  112. xoffset:(int)xoffset
  113. yoffset:(int)yoffset
  114. threshold:(int)threshold
  115. stride:(int)stride
  116. matrix:(ZXBitMatrix *)matrix {
  117. for (int y = 0, offset = yoffset * stride + xoffset; y < ZX_BLOCK_SIZE; y++, offset += stride) {
  118. for (int x = 0; x < ZX_BLOCK_SIZE; x++) {
  119. // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0
  120. if ((luminances[offset + x] & 0xFF) <= threshold) {
  121. [matrix setX:xoffset + x y:yoffset + y];
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * Calculates a single black point for each block of pixels and saves it away.
  128. * See the following thread for a discussion of this algorithm:
  129. * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
  130. */
  131. - (int **)calculateBlackPoints:(int8_t *)luminances
  132. subWidth:(int)subWidth
  133. subHeight:(int)subHeight
  134. width:(int)width
  135. height:(int)height {
  136. int **blackPoints = (int **)malloc(subHeight * sizeof(int *));
  137. for (int y = 0; y < subHeight; y++) {
  138. blackPoints[y] = (int *)malloc(subWidth * sizeof(int));
  139. int yoffset = y << ZX_BLOCK_SIZE_POWER;
  140. int maxYOffset = height - ZX_BLOCK_SIZE;
  141. if (yoffset > maxYOffset) {
  142. yoffset = maxYOffset;
  143. }
  144. for (int x = 0; x < subWidth; x++) {
  145. int xoffset = x << ZX_BLOCK_SIZE_POWER;
  146. int maxXOffset = width - ZX_BLOCK_SIZE;
  147. if (xoffset > maxXOffset) {
  148. xoffset = maxXOffset;
  149. }
  150. int sum = 0;
  151. int min = 0xFF;
  152. int max = 0;
  153. for (int yy = 0, offset = yoffset * width + xoffset; yy < ZX_BLOCK_SIZE; yy++, offset += width) {
  154. for (int xx = 0; xx < ZX_BLOCK_SIZE; xx++) {
  155. int pixel = luminances[offset + xx] & 0xFF;
  156. sum += pixel;
  157. // still looking for good contrast
  158. if (pixel < min) {
  159. min = pixel;
  160. }
  161. if (pixel > max) {
  162. max = pixel;
  163. }
  164. }
  165. // short-circuit min/max tests once dynamic range is met
  166. if (max - min > ZX_MIN_DYNAMIC_RANGE) {
  167. // finish the rest of the rows quickly
  168. for (yy++, offset += width; yy < ZX_BLOCK_SIZE; yy++, offset += width) {
  169. for (int xx = 0; xx < ZX_BLOCK_SIZE; xx++) {
  170. sum += luminances[offset + xx] & 0xFF;
  171. }
  172. }
  173. }
  174. }
  175. // The default estimate is the average of the values in the block.
  176. int average = sum >> (ZX_BLOCK_SIZE_POWER * 2);
  177. if (max - min <= ZX_MIN_DYNAMIC_RANGE) {
  178. // If variation within the block is low, assume this is a block with only light or only
  179. // dark pixels. In that case we do not want to use the average, as it would divide this
  180. // low contrast area into black and white pixels, essentially creating data out of noise.
  181. //
  182. // The default assumption is that the block is light/background. Since no estimate for
  183. // the level of dark pixels exists locally, use half the min for the block.
  184. average = min / 2;
  185. if (y > 0 && x > 0) {
  186. // Correct the "white background" assumption for blocks that have neighbors by comparing
  187. // the pixels in this block to the previously calculated black points. This is based on
  188. // the fact that dark barcode symbology is always surrounded by some amount of light
  189. // background for which reasonable black point estimates were made. The bp estimated at
  190. // the boundaries is used for the interior.
  191. // The (min < bp) is arbitrary but works better than other heuristics that were tried.
  192. int averageNeighborBlackPoint =
  193. (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4;
  194. if (min < averageNeighborBlackPoint) {
  195. average = averageNeighborBlackPoint;
  196. }
  197. }
  198. }
  199. blackPoints[y][x] = average;
  200. }
  201. }
  202. return blackPoints;
  203. }
  204. @end