tesseract  4.0.0-1-g2a2b
degradeimage.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: degradeimage.cpp
3  * Description: Function to degrade an image (usually of text) as if it
4  * has been printed and then scanned.
5  * Authors: Ray Smith
6  * Created: Tue Nov 19 2013
7  *
8  * (C) Copyright 2013, Google Inc.
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  **********************************************************************/
20 
21 #include "degradeimage.h"
22 
23 #include <cstdlib>
24 #include "allheaders.h" // from leptonica
25 #include "genericvector.h"
26 #include "helpers.h" // For TRand.
27 #include "rect.h"
28 
29 namespace tesseract {
30 
31 // A randomized perspective distortion can be applied to synthetic input.
32 // The perspective distortion comes from leptonica, which uses 2 sets of 4
33 // corners to determine the distortion. There are random values for each of
34 // the x numbers x0..x3 and y0..y3, except for x2 and x3 which are instead
35 // defined in terms of a single shear value. This reduces the degrees of
36 // freedom enough to make the distortion more realistic than it would otherwise
37 // be if all 8 coordinates could move independently.
38 // One additional factor is used for the color of the pixels that don't exist
39 // in the source image.
40 // Name for each of the randomizing factors.
50  // x2 = x1 - shear
51  // x3 = x0 + shear
53 };
54 
55 // Rotation is +/- kRotationRange radians.
56 const float kRotationRange = 0.02f;
57 // Number of grey levels to shift by for each exposure step.
58 const int kExposureFactor = 16;
59 // Salt and pepper noise is +/- kSaltnPepper.
60 const int kSaltnPepper = 5;
61 // Min sum of width + height on which to operate the ramp.
62 const int kMinRampSize = 1000;
63 
64 // Degrade the pix as if by a print/copy/scan cycle with exposure > 0
65 // corresponding to darkening on the copier and <0 lighter and 0 not copied.
66 // Exposures in [-2,2] are most useful, with -3 and 3 being extreme.
67 // If rotation is nullptr, rotation is skipped. If *rotation is non-zero, the
68 // pix is rotated by *rotation else it is randomly rotated and *rotation is
69 // modified.
70 //
71 // HOW IT WORKS:
72 // Most of the process is really dictated by the fact that the minimum
73 // available convolution is 3X3, which is too big really to simulate a
74 // good quality print/scan process. (2X2 would be better.)
75 // 1 pixel wide inputs are heavily smeared by the 3X3 convolution, making the
76 // images generally biased to being too light, so most of the work is to make
77 // them darker. 3 levels of thickening/darkening are achieved with 2 dilations,
78 // (using a greyscale erosion) one heavy (by being before convolution) and one
79 // light (after convolution).
80 // With no dilation, after covolution, the images are so light that a heavy
81 // constant offset is required to make the 0 image look reasonable. A simple
82 // constant offset multiple of exposure to undo this value is enough to achieve
83 // all the required lightening. This gives the advantage that exposure level 1
84 // with a single dilation gives a good impression of the broken-yet-too-dark
85 // problem that is often seen in scans.
86 // A small random rotation gives some varying greyscale values on the edges,
87 // and some random salt and pepper noise on top helps to realistically jaggy-up
88 // the edges.
89 // Finally a greyscale ramp provides a continuum of effects between exposure
90 // levels.
91 Pix* DegradeImage(Pix* input, int exposure, TRand* randomizer,
92  float* rotation) {
93  Pix* pix = pixConvertTo8(input, false);
94  pixDestroy(&input);
95  input = pix;
96  int width = pixGetWidth(input);
97  int height = pixGetHeight(input);
98  if (exposure >= 2) {
99  // An erosion simulates the spreading darkening of a dark copy.
100  // This is backwards to binary morphology,
101  // see http://www.leptonica.com/grayscale-morphology.html
102  pix = input;
103  input = pixErodeGray(pix, 3, 3);
104  pixDestroy(&pix);
105  }
106  // A convolution is essential to any mode as no scanner produces an
107  // image as sharp as the electronic image.
108  pix = pixBlockconv(input, 1, 1);
109  pixDestroy(&input);
110  // A small random rotation helps to make the edges jaggy in a realistic way.
111  if (rotation != nullptr) {
112  float radians_clockwise = 0.0f;
113  if (*rotation) {
114  radians_clockwise = *rotation;
115  } else if (randomizer != nullptr) {
116  radians_clockwise = randomizer->SignedRand(kRotationRange);
117  }
118 
119  input = pixRotate(pix, radians_clockwise,
120  L_ROTATE_AREA_MAP, L_BRING_IN_WHITE,
121  0, 0);
122  // Rotate the boxes to match.
123  *rotation = radians_clockwise;
124  pixDestroy(&pix);
125  } else {
126  input = pix;
127  }
128 
129  if (exposure >= 3 || exposure == 1) {
130  // Erosion after the convolution is not as heavy as before, so it is
131  // good for level 1 and in addition as a level 3.
132  // This is backwards to binary morphology,
133  // see http://www.leptonica.com/grayscale-morphology.html
134  pix = input;
135  input = pixErodeGray(pix, 3, 3);
136  pixDestroy(&pix);
137  }
138  // The convolution really needed to be 2x2 to be realistic enough, but
139  // we only have 3x3, so we have to bias the image darker or lose thin
140  // strokes.
141  int erosion_offset = 0;
142  // For light and 0 exposure, there is no dilation, so compensate for the
143  // convolution with a big darkening bias which is undone for lighter
144  // exposures.
145  if (exposure <= 0)
146  erosion_offset = -3 * kExposureFactor;
147  // Add in a general offset of the greyscales for the exposure level so
148  // a threshold of 128 gives a reasonable binary result.
149  erosion_offset -= exposure * kExposureFactor;
150  // Add a gradual fade over the page and a small amount of salt and pepper
151  // noise to simulate noise in the sensor/paper fibres and varying
152  // illumination.
153  l_uint32* data = pixGetData(input);
154  for (int y = 0; y < height; ++y) {
155  for (int x = 0; x < width; ++x) {
156  int pixel = GET_DATA_BYTE(data, x);
157  if (randomizer != nullptr)
158  pixel += randomizer->IntRand() % (kSaltnPepper*2 + 1) - kSaltnPepper;
159  if (height + width > kMinRampSize)
160  pixel -= (2*x + y) * 32 / (height + width);
161  pixel += erosion_offset;
162  if (pixel < 0)
163  pixel = 0;
164  if (pixel > 255)
165  pixel = 255;
166  SET_DATA_BYTE(data, x, pixel);
167  }
168  data += input->wpl;
169  }
170  return input;
171 }
172 
173 // Creates and returns a Pix distorted by various means according to the bool
174 // flags. If boxes is not nullptr, the boxes are resized/positioned according to
175 // any spatial distortion and also by the integer reduction factor box_scale
176 // so they will match what the network will output.
177 // Returns nullptr on error. The returned Pix must be pixDestroyed.
178 Pix* PrepareDistortedPix(const Pix* pix, bool perspective, bool invert,
179  bool white_noise, bool smooth_noise, bool blur,
180  int box_reduction, TRand* randomizer,
181  GenericVector<TBOX>* boxes) {
182  Pix* distorted = pixCopy(nullptr, const_cast<Pix*>(pix));
183  // Things to do to synthetic training data.
184  if (invert && randomizer->SignedRand(1.0) < 0)
185  pixInvert(distorted, distorted);
186  if ((white_noise || smooth_noise) && randomizer->SignedRand(1.0) > 0.0) {
187  // TODO(rays) Cook noise in a more thread-safe manner than rand().
188  // Attempt to make the sequences reproducible.
189  srand(randomizer->IntRand());
190  Pix* pixn = pixAddGaussianNoise(distorted, 8.0);
191  pixDestroy(&distorted);
192  if (smooth_noise) {
193  distorted = pixBlockconv(pixn, 1, 1);
194  pixDestroy(&pixn);
195  } else {
196  distorted = pixn;
197  }
198  }
199  if (blur && randomizer->SignedRand(1.0) > 0.0) {
200  Pix* blurred = pixBlockconv(distorted, 1, 1);
201  pixDestroy(&distorted);
202  distorted = blurred;
203  }
204  if (perspective)
205  GeneratePerspectiveDistortion(0, 0, randomizer, &distorted, boxes);
206  if (boxes != nullptr) {
207  for (int b = 0; b < boxes->size(); ++b) {
208  (*boxes)[b].scale(1.0f / box_reduction);
209  if ((*boxes)[b].width() <= 0)
210  (*boxes)[b].set_right((*boxes)[b].left() + 1);
211  }
212  }
213  return distorted;
214 }
215 
216 // Distorts anything that has a non-null pointer with the same pseudo-random
217 // perspective distortion. Width and height only need to be set if there
218 // is no pix. If there is a pix, then they will be taken from there.
219 void GeneratePerspectiveDistortion(int width, int height, TRand* randomizer,
220  Pix** pix, GenericVector<TBOX>* boxes) {
221  if (pix != nullptr && *pix != nullptr) {
222  width = pixGetWidth(*pix);
223  height = pixGetHeight(*pix);
224  }
225  float* im_coeffs = nullptr;
226  float* box_coeffs = nullptr;
227  l_int32 incolor =
228  ProjectiveCoeffs(width, height, randomizer, &im_coeffs, &box_coeffs);
229  if (pix != nullptr && *pix != nullptr) {
230  // Transform the image.
231  Pix* transformed = pixProjective(*pix, im_coeffs, incolor);
232  if (transformed == nullptr) {
233  tprintf("Projective transformation failed!!\n");
234  return;
235  }
236  pixDestroy(pix);
237  *pix = transformed;
238  }
239  if (boxes != nullptr) {
240  // Transform the boxes.
241  for (int b = 0; b < boxes->size(); ++b) {
242  int x1, y1, x2, y2;
243  const TBOX& box = (*boxes)[b];
244  projectiveXformSampledPt(box_coeffs, box.left(), height - box.top(), &x1,
245  &y1);
246  projectiveXformSampledPt(box_coeffs, box.right(), height - box.bottom(),
247  &x2, &y2);
248  TBOX new_box1(x1, height - y2, x2, height - y1);
249  projectiveXformSampledPt(box_coeffs, box.left(), height - box.bottom(),
250  &x1, &y1);
251  projectiveXformSampledPt(box_coeffs, box.right(), height - box.top(), &x2,
252  &y2);
253  TBOX new_box2(x1, height - y1, x2, height - y2);
254  (*boxes)[b] = new_box1.bounding_union(new_box2);
255  }
256  }
257  free(im_coeffs);
258  free(box_coeffs);
259 }
260 
261 // Computes the coefficients of a randomized projective transformation.
262 // The image transform requires backward transformation coefficient, and the
263 // box transform the forward coefficients.
264 // Returns the incolor arg to pixProjective.
265 int ProjectiveCoeffs(int width, int height, TRand* randomizer,
266  float** im_coeffs, float** box_coeffs) {
267  // Setup "from" points.
268  Pta* src_pts = ptaCreate(4);
269  ptaAddPt(src_pts, 0.0f, 0.0f);
270  ptaAddPt(src_pts, width, 0.0f);
271  ptaAddPt(src_pts, width, height);
272  ptaAddPt(src_pts, 0.0f, height);
273  // Extract factors from pseudo-random sequence.
274  float factors[FN_NUM_FACTORS];
275  float shear = 0.0f; // Shear is signed.
276  for (int i = 0; i < FN_NUM_FACTORS; ++i) {
277  // Everything is squared to make wild values rarer.
278  if (i == FN_SHEAR) {
279  // Shear is signed.
280  shear = randomizer->SignedRand(0.5 / 3.0);
281  shear = shear >= 0.0 ? shear * shear : -shear * shear;
282  // Keep the sheared points within the original rectangle.
283  if (shear < -factors[FN_X0]) shear = -factors[FN_X0];
284  if (shear > factors[FN_X1]) shear = factors[FN_X1];
285  factors[i] = shear;
286  } else if (i != FN_INCOLOR) {
287  factors[i] = fabs(randomizer->SignedRand(1.0));
288  if (i <= FN_Y3)
289  factors[i] *= 5.0 / 8.0;
290  else
291  factors[i] *= 0.5;
292  factors[i] *= factors[i];
293  }
294  }
295  // Setup "to" points.
296  Pta* dest_pts = ptaCreate(4);
297  ptaAddPt(dest_pts, factors[FN_X0] * width, factors[FN_Y0] * height);
298  ptaAddPt(dest_pts, (1.0f - factors[FN_X1]) * width, factors[FN_Y1] * height);
299  ptaAddPt(dest_pts, (1.0f - factors[FN_X1] + shear) * width,
300  (1 - factors[FN_Y2]) * height);
301  ptaAddPt(dest_pts, (factors[FN_X0] + shear) * width,
302  (1 - factors[FN_Y3]) * height);
303  getProjectiveXformCoeffs(dest_pts, src_pts, im_coeffs);
304  getProjectiveXformCoeffs(src_pts, dest_pts, box_coeffs);
305  ptaDestroy(&src_pts);
306  ptaDestroy(&dest_pts);
307  return factors[FN_INCOLOR] > 0.5f ? L_BRING_IN_WHITE : L_BRING_IN_BLACK;
308 }
309 
310 } // namespace tesseract
int size() const
Definition: genericvector.h:71
const int kExposureFactor
const int kMinRampSize
int32_t IntRand()
Definition: helpers.h:56
Definition: rect.h:34
Pix * PrepareDistortedPix(const Pix *pix, bool perspective, bool invert, bool white_noise, bool smooth_noise, bool blur, int box_reduction, TRand *randomizer, GenericVector< TBOX > *boxes)
const int kSaltnPepper
int16_t left() const
Definition: rect.h:72
Pix * DegradeImage(Pix *input, int exposure, TRand *randomizer, float *rotation)
int16_t top() const
Definition: rect.h:58
void GeneratePerspectiveDistortion(int width, int height, TRand *randomizer, Pix **pix, GenericVector< TBOX > *boxes)
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
double SignedRand(double range)
Definition: helpers.h:61
int16_t right() const
Definition: rect.h:79
int ProjectiveCoeffs(int width, int height, TRand *randomizer, float **im_coeffs, float **box_coeffs)
const float kRotationRange
int16_t bottom() const
Definition: rect.h:65