tesseract  4.0.0-1-g2a2b
thresholder.cpp
Go to the documentation of this file.
1 // File: thresholder.cpp
3 // Description: Base API for thresolding images in tesseract.
4 // Author: Ray Smith
5 // Created: Mon May 12 11:28:15 PDT 2008
6 //
7 // (C) Copyright 2008, Google Inc.
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 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 
20 #include "allheaders.h"
21 
22 #include "thresholder.h"
23 
24 #include <cstdint> // for uint32_t
25 #include <cstring>
26 
27 #include "otsuthr.h"
28 
29 #include "openclwrapper.h"
30 
31 namespace tesseract {
32 
34  : pix_(nullptr),
35  image_width_(0), image_height_(0),
36  pix_channels_(0), pix_wpl_(0),
37  scale_(1), yres_(300), estimated_res_(300) {
38  SetRectangle(0, 0, 0, 0);
39 }
40 
42  Clear();
43 }
44 
45 // Destroy the Pix if there is one, freeing memory.
47  pixDestroy(&pix_);
48 }
49 
50 // Return true if no image has been set.
52  return pix_ == nullptr;
53 }
54 
55 // SetImage makes a copy of all the image data, so it may be deleted
56 // immediately after this call.
57 // Greyscale of 8 and color of 24 or 32 bits per pixel may be given.
58 // Palette color images will not work properly and must be converted to
59 // 24 bit.
60 // Binary images of 1 bit per pixel may also be given but they must be
61 // byte packed with the MSB of the first byte being the first pixel, and a
62 // one pixel is WHITE. For binary images set bytes_per_pixel=0.
63 void ImageThresholder::SetImage(const unsigned char* imagedata,
64  int width, int height,
65  int bytes_per_pixel, int bytes_per_line) {
66  int bpp = bytes_per_pixel * 8;
67  if (bpp == 0) bpp = 1;
68  Pix* pix = pixCreate(width, height, bpp == 24 ? 32 : bpp);
69  l_uint32* data = pixGetData(pix);
70  int wpl = pixGetWpl(pix);
71  switch (bpp) {
72  case 1:
73  for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {
74  for (int x = 0; x < width; ++x) {
75  if (imagedata[x / 8] & (0x80 >> (x % 8)))
76  CLEAR_DATA_BIT(data, x);
77  else
78  SET_DATA_BIT(data, x);
79  }
80  }
81  break;
82 
83  case 8:
84  // Greyscale just copies the bytes in the right order.
85  for (int y = 0; y < height; ++y, data += wpl, imagedata += bytes_per_line) {
86  for (int x = 0; x < width; ++x)
87  SET_DATA_BYTE(data, x, imagedata[x]);
88  }
89  break;
90 
91  case 24:
92  // Put the colors in the correct places in the line buffer.
93  for (int y = 0; y < height; ++y, imagedata += bytes_per_line) {
94  for (int x = 0; x < width; ++x, ++data) {
95  SET_DATA_BYTE(data, COLOR_RED, imagedata[3 * x]);
96  SET_DATA_BYTE(data, COLOR_GREEN, imagedata[3 * x + 1]);
97  SET_DATA_BYTE(data, COLOR_BLUE, imagedata[3 * x + 2]);
98  }
99  }
100  break;
101 
102  case 32:
103  // Maintain byte order consistency across different endianness.
104  for (int y = 0; y < height; ++y, imagedata += bytes_per_line, data += wpl) {
105  for (int x = 0; x < width; ++x) {
106  data[x] = (imagedata[x * 4] << 24) | (imagedata[x * 4 + 1] << 16) |
107  (imagedata[x * 4 + 2] << 8) | imagedata[x * 4 + 3];
108  }
109  }
110  break;
111 
112  default:
113  tprintf("Cannot convert RAW image to Pix with bpp = %d\n", bpp);
114  }
115  pixSetYRes(pix, 300);
116  SetImage(pix);
117  pixDestroy(&pix);
118 }
119 
120 // Store the coordinates of the rectangle to process for later use.
121 // Doesn't actually do any thresholding.
122 void ImageThresholder::SetRectangle(int left, int top, int width, int height) {
123  rect_left_ = left;
124  rect_top_ = top;
125  rect_width_ = width;
126  rect_height_ = height;
127 }
128 
129 // Get enough parameters to be able to rebuild bounding boxes in the
130 // original image (not just within the rectangle).
131 // Left and top are enough with top-down coordinates, but
132 // the height of the rectangle and the image are needed for bottom-up.
133 void ImageThresholder::GetImageSizes(int* left, int* top,
134  int* width, int* height,
135  int* imagewidth, int* imageheight) {
136  *left = rect_left_;
137  *top = rect_top_;
138  *width = rect_width_;
139  *height = rect_height_;
140  *imagewidth = image_width_;
141  *imageheight = image_height_;
142 }
143 
144 // Pix vs raw, which to use? Pix is the preferred input for efficiency,
145 // since raw buffers are copied.
146 // SetImage for Pix clones its input, so the source pix may be pixDestroyed
147 // immediately after, but may not go away until after the Thresholder has
148 // finished with it.
149 void ImageThresholder::SetImage(const Pix* pix) {
150  if (pix_ != nullptr)
151  pixDestroy(&pix_);
152  Pix* src = const_cast<Pix*>(pix);
153  int depth;
154  pixGetDimensions(src, &image_width_, &image_height_, &depth);
155  // Convert the image as necessary so it is one of binary, plain RGB, or
156  // 8 bit with no colormap. Guarantee that we always end up with our own copy,
157  // not just a clone of the input.
158  if (pixGetColormap(src)) {
159  Pix* tmp = pixRemoveColormap(src, REMOVE_CMAP_BASED_ON_SRC);
160  depth = pixGetDepth(tmp);
161  if (depth > 1 && depth < 8) {
162  pix_ = pixConvertTo8(tmp, false);
163  pixDestroy(&tmp);
164  } else {
165  pix_ = tmp;
166  }
167  } else if (depth > 1 && depth < 8) {
168  pix_ = pixConvertTo8(src, false);
169  } else {
170  pix_ = pixCopy(nullptr, src);
171  }
172  depth = pixGetDepth(pix_);
173  pix_channels_ = depth / 8;
174  pix_wpl_ = pixGetWpl(pix_);
175  scale_ = 1;
176  estimated_res_ = yres_ = pixGetYRes(pix_);
177  Init();
178 }
179 
180 // Threshold the source image as efficiently as possible to the output Pix.
181 // Creates a Pix and sets pix to point to the resulting pointer.
182 // Caller must use pixDestroy to free the created Pix.
184 bool ImageThresholder::ThresholdToPix(PageSegMode pageseg_mode, Pix** pix) {
185  if (image_width_ > INT16_MAX || image_height_ > INT16_MAX) {
186  tprintf("Image too large: (%d, %d)\n", image_width_, image_height_);
187  return false;
188  }
189  if (pix_channels_ == 0) {
190  // We have a binary image, but it still has to be copied, as this API
191  // allows the caller to modify the output.
192  Pix* original = GetPixRect();
193  *pix = pixCopy(nullptr, original);
194  pixDestroy(&original);
195  } else {
197  }
198  return true;
199 }
200 
201 // Gets a pix that contains an 8 bit threshold value at each pixel. The
202 // returned pix may be an integer reduction of the binary image such that
203 // the scale factor may be inferred from the ratio of the sizes, even down
204 // to the extreme of a 1x1 pixel thresholds image.
205 // Ideally the 8 bit threshold should be the exact threshold used to generate
206 // the binary image in ThresholdToPix, but this is not a hard constraint.
207 // Returns nullptr if the input is binary. PixDestroy after use.
209  if (IsBinary()) return nullptr;
210  Pix* pix_grey = GetPixRectGrey();
211  int width = pixGetWidth(pix_grey);
212  int height = pixGetHeight(pix_grey);
213  int* thresholds;
214  int* hi_values;
215  OtsuThreshold(pix_grey, 0, 0, width, height, &thresholds, &hi_values);
216  pixDestroy(&pix_grey);
217  Pix* pix_thresholds = pixCreate(width, height, 8);
218  int threshold = thresholds[0] > 0 ? thresholds[0] : 128;
219  pixSetAllArbitrary(pix_thresholds, threshold);
220  delete [] thresholds;
221  delete [] hi_values;
222  return pix_thresholds;
223 }
224 
225 // Common initialization shared between SetImage methods.
228 }
229 
230 // Get a clone/copy of the source image rectangle.
231 // The returned Pix must be pixDestroyed.
232 // This function will be used in the future by the page layout analysis, and
233 // the layout analysis that uses it will only be available with Leptonica,
234 // so there is no raw equivalent.
236  if (IsFullImage()) {
237  // Just clone the whole thing.
238  return pixClone(pix_);
239  } else {
240  // Crop to the given rectangle.
241  Box* box = boxCreate(rect_left_, rect_top_, rect_width_, rect_height_);
242  Pix* cropped = pixClipRectangle(pix_, box, nullptr);
243  boxDestroy(&box);
244  return cropped;
245  }
246 }
247 
248 // Get a clone/copy of the source image rectangle, reduced to greyscale,
249 // and at the same resolution as the output binary.
250 // The returned Pix must be pixDestroyed.
251 // Provided to the classifier to extract features from the greyscale image.
253  Pix* pix = GetPixRect(); // May have to be reduced to grey.
254  int depth = pixGetDepth(pix);
255  if (depth != 8) {
256  Pix* result = depth < 8 ? pixConvertTo8(pix, false)
257  : pixConvertRGBToLuminance(pix);
258  pixDestroy(&pix);
259  return result;
260  }
261  return pix;
262 }
263 
264 // Otsu thresholds the rectangle, taking the rectangle from *this.
266  Pix** out_pix) const {
267  PERF_COUNT_START("OtsuThresholdRectToPix")
268  int* thresholds;
269  int* hi_values;
270 
271  int num_channels = OtsuThreshold(src_pix, rect_left_, rect_top_, rect_width_,
272  rect_height_, &thresholds, &hi_values);
273  // only use opencl if compiled w/ OpenCL and selected device is opencl
274 #ifdef USE_OPENCL
275  OpenclDevice od;
276  if (num_channels == 4 &&
277  od.selectedDeviceIsOpenCL() && rect_top_ == 0 && rect_left_ == 0) {
278  od.ThresholdRectToPixOCL((unsigned char*)pixGetData(src_pix), num_channels,
279  pixGetWpl(src_pix) * 4, thresholds, hi_values,
280  out_pix /*pix_OCL*/, rect_height_, rect_width_,
282  } else {
283 #endif
284  ThresholdRectToPix(src_pix, num_channels, thresholds, hi_values, out_pix);
285 #ifdef USE_OPENCL
286  }
287 #endif
288  delete [] thresholds;
289  delete [] hi_values;
290 
292 }
293 
297 // arrays and also the bytes per pixel in src_pix.
299  int num_channels,
300  const int* thresholds,
301  const int* hi_values,
302  Pix** pix) const {
303  PERF_COUNT_START("ThresholdRectToPix")
304  *pix = pixCreate(rect_width_, rect_height_, 1);
305  uint32_t* pixdata = pixGetData(*pix);
306  int wpl = pixGetWpl(*pix);
307  int src_wpl = pixGetWpl(src_pix);
308  uint32_t* srcdata = pixGetData(src_pix);
309  for (int y = 0; y < rect_height_; ++y) {
310  const uint32_t* linedata = srcdata + (y + rect_top_) * src_wpl;
311  uint32_t* pixline = pixdata + y * wpl;
312  for (int x = 0; x < rect_width_; ++x) {
313  bool white_result = true;
314  for (int ch = 0; ch < num_channels; ++ch) {
315  int pixel =
316  GET_DATA_BYTE(linedata, (x + rect_left_) * num_channels + ch);
317  if (hi_values[ch] >= 0 &&
318  (pixel > thresholds[ch]) == (hi_values[ch] == 0)) {
319  white_result = false;
320  break;
321  }
322  }
323  if (white_result)
324  CLEAR_DATA_BIT(pixline, x);
325  else
326  SET_DATA_BIT(pixline, x);
327  }
328  }
329 
331 }
332 
333 } // namespace tesseract.
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: thresholder.cpp:63
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
Definition: thresholder.cpp:46
virtual Pix * GetPixRectGrey()
#define PERF_COUNT_START(FUNCT_NAME)
virtual Pix * GetPixRectThresholds()
bool IsEmpty() const
Return true if no image has been set.
Definition: thresholder.cpp:51
bool IsFullImage() const
Return true if we are processing the full image.
Definition: thresholder.h:153
void OtsuThresholdRectToPix(Pix *src_pix, Pix **out_pix) const
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
bool IsBinary() const
Returns true if the source image is binary.
Definition: thresholder.h:75
void SetRectangle(int left, int top, int width, int height)
virtual void Init()
Common initialization shared between SetImage methods.
void ThresholdRectToPix(Pix *src_pix, int num_channels, const int *thresholds, const int *hi_values, Pix **pix) const
#define PERF_COUNT_END
int OtsuThreshold(Pix *src_pix, int left, int top, int width, int height, int **thresholds, int **hi_values)
Definition: otsuthr.cpp:39
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
virtual bool ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
Returns false on error.