aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/image/kernels/single_image_random_dot_stereograms_ops.cc
blob: 23efd359d578c05afa0bb6766b9ed2661dc10d78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

using shape_inference::InferenceContext;

template <typename T>
class SingleImageRandomDotStereogramsOp : public OpKernel {
 private:
  int E2Epixels;  // Pixels from eye to eye = eye_to_eye_inches * DPI

  int input_Xvalue;  // X value of input Z values (width)
  int input_Yvalue;  // Y value of input Z values (height)

  int output_Ximage;  // X value of output image (width)
  int output_Yimage;  // Y value of output image (height)
  int output_Cimage;  // color value of output image (color, 1 or 3)  (3 not
                      // implemented)

  int data_box_left;    // X starting value for DATA window
  int data_box_top;     // Y starting value for DATA window
  int data_box_width;   // width of scan line
  int data_box_height;  // hight of image

  int converge_dot_box_end;  // Row convergences dots end on

  uint8* outputImage;  // Output Image flat as a buffer (Tensor Connection)
  double* ZBuffer;     // For internal use, allow for MASK, etc later, actual Z
                       // used for Stereogram, XxY (X is the row index, y is col
                       // index like a screen)
                       // 0 (far) -> 1.0(near) range
  bool hidden_surface_removal;
  int convergence_dots_size;
  int dots_per_inch;
  float eye_separation;
  float mu;
  bool normalize;
  float normalize_max;
  float normalize_min;
  float border_level;
  int number_colors;
  ::tensorflow::TensorShapeProto output_image_shape;
  ::tensorflow::TensorShapeProto output_data_window;

  uint8 Cblack = (uint8)0;
  uint8 Cwhite = (uint8)255;

  int indexMode = 0;  // 0 - truncate XY, 1 - round XY, 2 - Interpolate XY (not
                      // implemented yet, keep default of 0)
  int interp_x, interp_y;  // 1 - yes, 0 - no  interpolation directions (not
                           // implemented yet)

  bool debugging = false;

  inline int separation(double z) {
    return (std::round((1 - mu * z) * E2Epixels / (2 - mu * z)));
  }

  inline int get_far_width() { return (separation(0.0)); }
  inline int get_near_width() { return (separation(1.0)); }

 public:
  explicit SingleImageRandomDotStereogramsOp(OpKernelConstruction* context)
      : OpKernel(context) {  // Constructor
    OP_REQUIRES_OK(context, context->GetAttr("hidden_surface_removal",
                                             &hidden_surface_removal));
    OP_REQUIRES_OK(context, context->GetAttr("convergence_dots_size",
                                             &convergence_dots_size));
    OP_REQUIRES_OK(context, context->GetAttr("dots_per_inch", &dots_per_inch));
    OP_REQUIRES_OK(context,
                   context->GetAttr("eye_separation", &eye_separation));
    OP_REQUIRES_OK(context, context->GetAttr("mu", &mu));
    OP_REQUIRES_OK(context, context->GetAttr("normalize", &normalize));
    OP_REQUIRES_OK(context, context->GetAttr("normalize_max", &normalize_max));
    OP_REQUIRES_OK(context, context->GetAttr("normalize_min", &normalize_min));
    OP_REQUIRES_OK(context, context->GetAttr("border_level", &border_level));
    OP_REQUIRES_OK(context, context->GetAttr("number_colors", &number_colors));
    OP_REQUIRES_OK(context,
                   context->GetAttr("output_image_shape", &output_image_shape));
    OP_REQUIRES_OK(context,
                   context->GetAttr("output_data_window", &output_data_window));

    E2Epixels =
        eye_separation * dots_per_inch;  // Initialize pixels from eye to eye
  }

  ~SingleImageRandomDotStereogramsOp() {  // Destructor
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& input_tensor = context->input(0);
    input_Xvalue = input_tensor.shape().dim_size(
        1);  // X value is the number of columns of the input matrix
    input_Yvalue =
        input_tensor.shape().dim_size(0);  // Y value is the number of rows

    output_Ximage = output_image_shape.dim(0).size();
    output_Yimage = output_image_shape.dim(1).size();
    output_Cimage = output_image_shape.dim(2).size();

    if (number_colors > 256)  // Go to full color image
      output_Cimage = 3;

    int data_Xwindow = output_data_window.dim(0).size();
    int data_Ywindow = output_data_window.dim(1).size();

    int deltaX_border_image = output_Ximage - data_Xwindow;
    int deltaY_border_image = output_Yimage - data_Ywindow;

    if (convergence_dots_size >
        0)  // 3 frame sections in Y direction due to DOTS
    {
      deltaY_border_image =
          deltaY_border_image -
          convergence_dots_size;  // Take off space for Convergence Dots
      deltaY_border_image = std::max(0, deltaY_border_image);
      data_box_top = deltaY_border_image / 3;

      if (deltaY_border_image >= 0) {
        converge_dot_box_end = output_Yimage - 1 - data_box_top;
      } else {
        converge_dot_box_end = output_Yimage - 1;
      }
    } else  // Otherwise only 2, no convergence dot
    {
      data_box_top = deltaY_border_image / 2;  // Center DATA in Y dimension
      converge_dot_box_end = output_Yimage - 1;
    }

    data_box_left = deltaX_border_image / 2;  // Center DATA in X dimension
    data_box_width = data_Xwindow;             // width of scan line
    data_box_height = data_Ywindow;            // hight of image

    const T* inputZ = input_tensor.flat<T>().data();  // Flatten input Z buffer

    BuildZBuffer(inputZ);

    // Output a scalar string.
    Tensor* output_tensor = NULL;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            0, TensorShape({output_Yimage, output_Ximage, output_Cimage}),
            &output_tensor));

    outputImage = output_tensor->flat<uint8>().data();

    generate_stereogram();

    delete[] ZBuffer;
  }

  //***************************************************************************
  //***************************************************************************
  // Move input into standard Z format to reduce complexity of algorithm
  //
  void BuildZBuffer(const T* Z, bool log = false) {
    double MaxValue = 1.0;
    double MinValue = 0.0;
    ZBuffer = new double[input_Xvalue * input_Yvalue];  // Used to computer
                                                        // final Z values before
                                                        // rendering to output

    if (normalize) {
      // Init Min/Max to first value
      if (normalize_max < normalize_min)  // Autoscale if MIN>MAX
      {
        MaxValue = (double)*Z;
        MinValue = (double)*Z;

        for (int y = 0; y < input_Yvalue; ++y)
          for (int x = 0; x < input_Xvalue; ++x) {
            double value = getZfromInputImage(Z, x, y);
            if (value > MaxValue) MaxValue = value;
            if (value < MinValue) MinValue = value;
          }
      } else {
        MaxValue = normalize_max;
        MinValue = normalize_min;
      }
    }

    for (int y = 0; y < input_Yvalue; ++y)
      for (int x = 0; x < input_Xvalue; ++x) {
        double value = getZfromInputImage(Z, x, y);

        if (normalize) {
          value = (value - MinValue) / (MaxValue - MinValue);
        }

        if (value > 1.0) value = 1.0;
        if (value < 0.0) value = 0.0;

        *(ZBuffer + (input_Xvalue * y + x)) = value;
      }
  }

  //***************************************************************************
  //***************************************************************************
  double getZfromInputImage(const T* Z, int x, int y) {
    double return_val;

    return_val = (double)*(Z + input_Xvalue * y + x);  // Get value
    return return_val;
  }

  //***************************************************************************
  //***************************************************************************
  // All normalized, not checking required
  // Possible Projection issue if DATA is bigger or smaller than Input
  //  Modes include:
  //         Truncate value (Default)
  //         Round-off value
  //         Interpolate between values
  //
  double getZfromZbuffer(double x, double y) {
    int xi, yi;

    switch (indexMode) {
      case 0:  // Truncate
        xi = int(x);
        yi = int(y);
        return (*(ZBuffer + (xi + input_Xvalue * yi)));
        break;
      case 1:  // Round-off
        xi = std::round(x);
        yi = std::round(y);
        return (*(ZBuffer + (xi + input_Xvalue * yi)));
        break;
      case 2:  // Interpolate (Not implemented yet, will need 4 points
               // [x,y],[x+1,y],[x,y+1],[x+1,y+1], then interpolate)
        xi = int(x);
        yi = int(y);
        return (*(ZBuffer + (xi + input_Xvalue * yi)));
        break;
      default:  // Round-off is the default
        xi = int(x + 0.5);
        yi = int(y + 0.5);
        return (*(ZBuffer + (xi + input_Xvalue * yi)));
        break;
    }
  }

  //***************************************************************************
  //***************************************************************************

  int getOutputImageIndex(int x, int y,
                          int channel) {  // No error checking for some
                                          // optimization, calling routine
                                          // required to make sure there is no
                                          // violation
    return ((output_Ximage * output_Cimage) * y + x * output_Cimage + channel);
  }

  //***************************************************************************
  //***************************************************************************

  double getZFromOutputPixel(int x, int y) {
    double xofz, yofz, returnval;

    // Convert pixel units to Z units, do this as "double"

    xofz =
        (double)input_Xvalue * (x - data_box_left) / ((double)data_box_width);
    yofz =
        (double)input_Yvalue * (y - data_box_top) / ((double)data_box_height);

    if ((xofz < 0) || (yofz < 0) || (yofz >= input_Yvalue) ||
        (xofz >= input_Xvalue)) {  // Top of left side border hit or  Right
                                   // side or bottom border hit
                                   // Send BORDER Z value
      return (border_level);
    }

    {  // in data set Z interpolate if need
      double gz;

      gz = getZfromZbuffer(xofz, yofz);

      returnval = gz;
    }

    return (returnval);
  }

  //***************************************************************************
  //***************************************************************************

  void generate_stereogram() {
    int s, left, right, visible, t, l;
    double zt, gz;
    // Scan line
    uint8* pix;  // Scan row color for each pixel
    int* same;   // Used to determine if Pixel needs to be the same as another
                 // pixel in the row

    pix = new uint8[output_Ximage * output_Cimage];
    same = new int[output_Ximage];

    for (int y = 0; y < output_Yimage; ++y) {
      // Set no dependencies on any pixels, tie each one back to itself
      for (int x = 0; x < output_Ximage; ++x) same[x] = x;

      for (int x = 0; x < output_Ximage; ++x) {
        gz = getZFromOutputPixel(x, y);
        s = separation(gz);
        left = x - s / 2;
        right = left + s;

        if ((left >= 0) && (right < output_Ximage)) {
          t = 1;
          visible = 1;
          if (hidden_surface_removal) do {
              zt = gz + 2 * (2 - mu * gz) * t / (mu * E2Epixels);
              visible = (getZFromOutputPixel(x - t, y) < zt) &&
                        (getZFromOutputPixel(x + t, y) < zt);
              ++t;
            } while ((visible) && (zt < 1));

          if (visible) {
            l = same[left];
            while ((l != left) && (l != right))
              if (l < right) {
                left = l;
                l = same[left];
              } else {
                same[left] = right;
                left = right;
                l = same[left];
                right = l;
              }
            same[left] = right;
          }
        }
      }
      // Set colors for scan row, use channels and number_colors
      for (int x = output_Ximage - 1; x >= 0; x--) {
        for (int channel = 0; channel < output_Cimage; ++channel) {
          if (same[x] == x) {  // Pick a random color
            if (number_colors == 2) {
              if ((rand() % 2) == 0) {
                pix[x * output_Cimage + channel] = Cblack;
              } else {
                pix[x * output_Cimage + channel] = Cwhite;
              }
            } else {
              pix[x * output_Cimage + channel] = rand() % 256;
            }
          } else
            pix[x * output_Cimage + channel] =
                pix[same[x] * output_Cimage + channel];

          setpixel(x, y, channel, pix[x * output_Cimage + channel]);
        }
      }
    }

    draw_convergence_dots();

    delete[] pix;
    delete[] same;
  }

  //***************************************************************************
  //***************************************************************************

  void draw_convergence_dots() {
    int x1, x2;  // center position for convergence dots

    if (convergence_dots_size == 0)  // No dot, return
      return;

    x1 = output_Ximage / 2 - get_far_width() / 2;
    x2 = output_Ximage / 2 + get_far_width() / 2;

    for (int lloop = 0; lloop < convergence_dots_size; ++lloop)
      for (int wloop = 0; wloop < convergence_dots_size; ++wloop)
        for (int channel = 0; channel < output_Cimage; ++channel) {
          setpixel(x1 - (convergence_dots_size / 2) + wloop,
                   converge_dot_box_end - lloop, channel, Cblack);
          setpixel(x2 - (convergence_dots_size / 2) + wloop,
                   converge_dot_box_end - lloop, channel, Cblack);
        }
  }

  //***************************************************************************
  //***************************************************************************

  void setpixel(int x, int y, int channel, uint8 color) {
    *(outputImage + getOutputImageIndex(x, y, channel)) = color;
  }
};

#define REGISTER_KERNEL(T)                                        \
  REGISTER_KERNEL_BUILDER(Name("SingleImageRandomDotStereograms") \
                              .Device(DEVICE_CPU)                 \
                              .TypeConstraint<T>("T"),            \
                          SingleImageRandomDotStereogramsOp<T>);

REGISTER_KERNEL(int32);
REGISTER_KERNEL(int64);
REGISTER_KERNEL(float);
REGISTER_KERNEL(double);

#undef REGISTER_KERNEL

}  // end namespace tensorflow