pointset_processing.cpp 31.1 KB
Newer Older
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
1
/* The copyright in this software is being made available under the BSD
David Flynn's avatar
David Flynn committed
2
3
4
 * Licence, included below.  This software may be subject to other third
 * party and contributor rights, including patent rights, and no such
 * rights are granted under this licence.
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
5
 *
David Flynn's avatar
David Flynn committed
6
 * Copyright (c) 2017-2018, ISO/IEC
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
7
8
9
10
11
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
David Flynn's avatar
David Flynn committed
12
13
14
15
16
17
18
19
20
21
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the ISO/IEC nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
22
23
24
25
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
David Flynn's avatar
David Flynn committed
26
27
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
28
29
30
31
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
David Flynn's avatar
David Flynn committed
32
33
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
34
35
 */

36
37
#include "pointset_processing.h"

38
#include "colourspace.h"
39
#include "hls.h"
40
#include "KDTreeVectorOfVectorsAdaptor.h"
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
41

David Flynn's avatar
David Flynn committed
42
#include <cstddef>
43
#include <set>
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
44
#include <vector>
45
46
#include <utility>
#include <map>
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
47
48
49

namespace pcc {

50
51
//============================================================================
// Quantise the geometry of a point cloud, retaining unique points only.
52
// Points in the @src point cloud are translated by -@offset, quantised by a
53
// multiplicitive @scaleFactor with rounding, then clamped to @clamp.
54
55
56
57
58
//
// The destination and source point clouds may be the same object.
//
// NB: attributes are not processed.

59
void
60
61
quantizePositionsUniq(
  const float scaleFactor,
62
  const Vec3<int> offset,
63
  const Box3<int> clamp,
64
  const PCCPointSet3& src,
65
66
  PCCPointSet3* dst,
  std::multimap<Vec3<double>, int32_t>& doubleQuantizedToOrigin)
67
68
69
{
  // Determine the set of unique quantised points

70
  std::multimap<Vec3<int32_t>, int32_t> intQuantizedToOrigin;
71
  std::set<Vec3<int32_t>> uniquePoints;
72
73
  int numSrcPoints = src.getPointCount();
  for (int i = 0; i < numSrcPoints; ++i) {
74
    const Vec3<double>& point = src[i];
75

76
    Vec3<int32_t> quantizedPoint;
77
    for (int k = 0; k < 3; k++) {
78
79
      double k_pos = std::round((point[k] - offset[k]) * scaleFactor);
      quantizedPoint[k] = PCCClip(int32_t(k_pos), clamp.min[k], clamp.max[k]);
80
    }
81
82

    uniquePoints.insert(quantizedPoint);
83
    intQuantizedToOrigin.insert(std::make_pair(quantizedPoint, i));
84
85
86
87
88
89
90
91
92
  }

  // Populate output point cloud

  if (&src != dst) {
    dst->clear();
    dst->addRemoveAttributes(src.hasColors(), src.hasReflectances());
  }
  dst->resize(uniquePoints.size());
93
  doubleQuantizedToOrigin.clear();
94
95
96
97
98
99

  int idx = 0;
  for (const auto& point : uniquePoints) {
    auto& dstPoint = (*dst)[idx++];
    for (int k = 0; k < 3; ++k)
      dstPoint[k] = double(point[k]);
100
101
102
103
104
    std::multimap<Vec3<int32_t>, int32_t>::iterator pos;
    for (pos = intQuantizedToOrigin.lower_bound(point);
         pos != intQuantizedToOrigin.upper_bound(point); ++pos) {
      doubleQuantizedToOrigin.insert(std::make_pair(dstPoint, pos->second));
    }
105
106
107
108
109
  }
}

//============================================================================
// Quantise the geometry of a point cloud, retaining duplicate points.
110
// Points in the @src point cloud are translated by -@offset, then quantised
111
112
113
114
115
116
// by a multiplicitive @scaleFactor with rounding.
//
// The destination and source point clouds may be the same object.
//
// NB: attributes are preserved

117
void
118
119
quantizePositions(
  const float scaleFactor,
120
  const Vec3<int> offset,
121
  const Box3<int> clamp,
122
123
124
125
126
127
128
129
130
131
132
133
  const PCCPointSet3& src,
  PCCPointSet3* dst)
{
  int numSrcPoints = src.getPointCount();

  // In case dst and src point clouds are the same, don't destroy src.
  if (&src != dst) {
    dst->clear();
    dst->addRemoveAttributes(src.hasColors(), src.hasReflectances());
    dst->resize(numSrcPoints);
  }

134
  Box3<double> clampD{
135
136
137
138
    {double(clamp.min[0]), double(clamp.min[1]), double(clamp.min[2])},
    {double(clamp.max[0]), double(clamp.max[1]), double(clamp.max[2])},
  };

139
  for (int i = 0; i < numSrcPoints; ++i) {
140
    const Vec3<double> point = src[i];
141
    auto& dstPoint = (*dst)[i];
142
143
144
145
    for (int k = 0; k < 3; ++k) {
      double k_pos = std::round((point[k] - offset[k]) * scaleFactor);
      dstPoint[k] = PCCClip(k_pos, clampD.min[k], clampD.max[k]);
    }
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
  }

  // don't copy attributes if dst already has them
  if (&src == dst)
    return;

  if (src.hasColors()) {
    for (int i = 0; i < numSrcPoints; ++i)
      dst->setColor(i, src.getColor(i));
  }

  if (src.hasReflectances()) {
    for (int i = 0; i < numSrcPoints; ++i)
      dst->setReflectance(i, src.getReflectance(i));
  }
}

163
164
165
//============================================================================
// Clamp point co-ordinates in @cloud to @bbox, preserving attributes.

166
void
167
clampVolume(Box3<double> bbox, PCCPointSet3* cloud)
168
169
170
171
172
173
174
175
176
177
{
  int numSrcPoints = cloud->getPointCount();

  for (int i = 0; i < numSrcPoints; ++i) {
    auto& point = (*cloud)[i];
    for (int k = 0; k < 3; ++k)
      point[k] = PCCClip(point[k], bbox.min[k], bbox.max[k]);
  }
}

178
179
//============================================================================
// Determine colour attribute values from a reference/source point cloud.
180
181
182
183
184
185
186
187
188
// For each point of the target p_t:
//  - Find the N_1 (1 < N_1) nearest neighbours in source to p_t and create
//    a set of points denoted by Ψ_1.
//  - Find the set of source points that p_t belongs to their set of N_2
//    nearest neighbours. Denote this set of points by Ψ_2.
//  - Compute the distance-weighted average of points in Ψ_1 and Ψ_2 by:
//        \bar{Ψ}_k = ∑_{q∈Ψ_k} c(q)/Δ(q,p_t)
//                    ----------------------- ,
//                    ∑_{q∈Ψ_k} 1/Δ(q,p_t)
189
//
190
191
192
193
// where Δ(a,b) denotes the Euclidian distance between the points a and b,
// and c(q) denotes the colour of point q.  Compute the average (or the
// weighted average with the number of points of each set as the weights)
// of \bar{Ψ}̅_1 and \bar{Ψ}̅_2 and transfer it to p_t.
194
195
196
197
198
//
// Differences in the scale and translation of the target and source point
// clouds, is handled according to:
//    posInTgt = (posInSrc - targetToSourceOffset) * sourceToTargetScaleFactor

199
bool
200
recolourColour(
201
  const AttributeDescription& attrDesc,
202
  const RecolourParams& params,
203
204
  const PCCPointSet3& source,
  double sourceToTargetScaleFactor,
205
  Vec3<double> targetToSourceOffset,
206
  PCCPointSet3& target)
207
{
208
209
  double targetToSourceScaleFactor = 1.0 / sourceToTargetScaleFactor;

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
210
211
212
213
214
  const size_t pointCountSource = source.getPointCount();
  const size_t pointCountTarget = target.getPointCount();
  if (!pointCountSource || !pointCountTarget || !source.hasColors()) {
    return false;
  }
215

216
217
218
219
  KDTreeVectorOfVectorsAdaptor<PCCPointSet3, double> kdtreeTarget(
    3, target, 10);
  KDTreeVectorOfVectorsAdaptor<PCCPointSet3, double> kdtreeSource(
    3, source, 10);
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
220
221

  target.addColors();
222
  std::vector<Vec3<attr_t>> refinedColors1;
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
223
  refinedColors1.resize(pointCountTarget);
224

225
226
227
  Vec3<double> clipMax{double((1 << attrDesc.attr_bitdepth) - 1),
                       double((1 << attrDesc.attr_bitdepth_secondary) - 1),
                       double((1 << attrDesc.attr_bitdepth_secondary) - 1)};
228

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  double maxGeometryDist2Fwd = params.maxGeometryDist2Fwd < 512
    ? params.maxGeometryDist2Fwd
    : std::numeric_limits<double>::max();
  double maxGeometryDist2Bwd = params.maxGeometryDist2Bwd < 512
    ? params.maxGeometryDist2Bwd
    : std::numeric_limits<double>::max();
  double maxAttributeDist2Fwd = params.maxAttributeDist2Fwd < 512
    ? params.maxAttributeDist2Fwd
    : std::numeric_limits<double>::max();
  double maxAttributeDist2Bwd = params.maxAttributeDist2Bwd < 512
    ? params.maxAttributeDist2Bwd
    : std::numeric_limits<double>::max();

  // Forward direction
  const int num_resultsFwd = params.numNeighboursFwd;
  nanoflann::KNNResultSet<double> resultSetFwd(num_resultsFwd);
  std::vector<size_t> indicesFwd(num_resultsFwd);
  std::vector<double> sqrDistFwd(num_resultsFwd);
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
247
  for (size_t index = 0; index < pointCountTarget; ++index) {
248
    resultSetFwd.init(&indicesFwd[0], &sqrDistFwd[0]);
249

250
    Vec3<double> posInSrc =
251
252
      target[index] * targetToSourceScaleFactor + targetToSourceOffset;

253
    kdtreeSource.index->findNeighbors(
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
      resultSetFwd, &posInSrc[0], nanoflann::SearchParams(10));

    while (1) {
      if (indicesFwd.size() == 1)
        break;

      if (sqrDistFwd[int(resultSetFwd.size()) - 1] <= maxGeometryDist2Fwd)
        break;

      sqrDistFwd.pop_back();
      indicesFwd.pop_back();
    }

    bool isDone = false;
    if (params.skipAvgIfIdenticalSourcePointPresentFwd) {
      if (sqrDistFwd[0] < 0.0001) {
        refinedColors1[index] = source.getColor(indicesFwd[0]);
        isDone = true;
      }
    }

    if (isDone)
      continue;

    int nNN = indicesFwd.size();
    while (nNN > 0 && !isDone) {
      if (nNN == 1) {
        refinedColors1[index] = source.getColor(indicesFwd[0]);
        isDone = true;
        break;
      }

286
      std::vector<Vec3<attr_t>> colors;
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
      colors.resize(0);
      colors.resize(nNN);
      for (int i = 0; i < nNN; ++i) {
        for (int k = 0; k < 3; ++k) {
          colors[i][k] = double(source.getColor(indicesFwd[i])[k]);
        }
      }
      double maxAttributeDist2 = std::numeric_limits<double>::min();
      for (int i = 0; i < nNN; ++i) {
        for (int j = 0; j < nNN; ++j) {
          const double dist2 = (colors[i] - colors[j]).getNorm2();
          if (dist2 > maxAttributeDist2) {
            maxAttributeDist2 = dist2;
          }
        }
      }
      if (maxAttributeDist2 > maxAttributeDist2Fwd) {
        --nNN;
      } else {
        Vec3<double> refinedColor(0.0);
        if (params.useDistWeightedAvgFwd) {
          double sumWeights{0.0};
          for (int i = 0; i < nNN; ++i) {
            const double weight = 1 / (sqrDistFwd[i] + params.distOffsetFwd);
            for (int k = 0; k < 3; ++k) {
              refinedColor[k] += source.getColor(indicesFwd[i])[k] * weight;
            }
            sumWeights += weight;
          }
          refinedColor /= sumWeights;
        } else {
          for (int i = 0; i < nNN; ++i) {
            for (int k = 0; k < 3; ++k) {
              refinedColor[k] += source.getColor(indicesFwd[i])[k];
            }
          }
          refinedColor /= nNN;
        }
        for (int k = 0; k < 3; ++k) {
          refinedColors1[index][k] =
327
            attr_t(PCCClip(round(refinedColor[k]), 0.0, clipMax[k]));
328
329
330
331
        }
        isDone = true;
      }
    }
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
332
  }
333

334
335
336
337
338
339
340
341
  // Backward direction
  const size_t num_resultsBwd = params.numNeighboursBwd;
  std::vector<size_t> indicesBwd(num_resultsBwd);
  std::vector<double> sqrDistBwd(num_resultsBwd);
  nanoflann::KNNResultSet<double> resultSetBwd(num_resultsBwd);

  struct DistColor {
    double dist;
342
    Vec3<attr_t> color;
343
344
345
346
  };
  std::vector<std::vector<DistColor>> refinedColorsDists2;
  refinedColorsDists2.resize(pointCountTarget);

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
347
  for (size_t index = 0; index < pointCountSource; ++index) {
348
    const Vec3<attr_t> color = source.getColor(index);
349
    resultSetBwd.init(&indicesBwd[0], &sqrDistBwd[0]);
350

351
    Vec3<double> posInTgt =
352
353
      (source[index] - targetToSourceOffset) * sourceToTargetScaleFactor;

354
    kdtreeTarget.index->findNeighbors(
355
356
357
358
359
360
361
362
363
364
365
366
367
368
      resultSetBwd, &posInTgt[0], nanoflann::SearchParams(10));

    for (int i = 0; i < num_resultsBwd; ++i) {
      if (sqrDistBwd[i] <= maxGeometryDist2Bwd) {
        refinedColorsDists2[indicesBwd[i]].push_back(
          DistColor{sqrDistBwd[i], color});
      }
    }
  }

  for (size_t index = 0; index < pointCountTarget; ++index) {
    std::sort(
      refinedColorsDists2[index].begin(), refinedColorsDists2[index].end(),
      [](DistColor& dc1, DistColor& dc2) { return dc1.dist < dc2.dist; });
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
369
  }
370

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
371
  for (size_t index = 0; index < pointCountTarget; ++index) {
372
    const Vec3<attr_t> color1 = refinedColors1[index];
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
    auto& colorsDists2 = refinedColorsDists2[index];
    if (colorsDists2.empty()) {
      target.setColor(index, color1);
      continue;
    }

    bool isDone = false;
    const Vec3<double> centroid1(color1[0], color1[1], color1[2]);
    Vec3<double> centroid2(0.0);
    if (params.skipAvgIfIdenticalSourcePointPresentBwd) {
      if (colorsDists2[0].dist < 0.0001) {
        auto temp = colorsDists2[0];
        colorsDists2.clear();
        colorsDists2.push_back(temp);
        for (int k = 0; k < 3; ++k) {
          centroid2[k] = colorsDists2[0].color[k];
        }
        isDone = true;
      }
    }

    if (!isDone) {
      int nNN = colorsDists2.size();
      while (nNN > 0 && !isDone) {
        nNN = colorsDists2.size();
        if (nNN == 1) {
          auto temp = colorsDists2[0];
          colorsDists2.clear();
          colorsDists2.push_back(temp);
          for (int k = 0; k < 3; ++k) {
            centroid2[k] = colorsDists2[0].color[k];
          }
          isDone = true;
        }
        if (!isDone) {
          std::vector<Vec3<double>> colors;
          colors.resize(0);
          colors.resize(nNN);
          for (int i = 0; i < nNN; ++i) {
            for (int k = 0; k < 3; ++k) {
              colors[i][k] = double(colorsDists2[i].color[k]);
            }
          }
          double maxAttributeDist2 = std::numeric_limits<double>::min();
          for (int i = 0; i < nNN; ++i) {
            for (int j = 0; j < nNN; ++j) {
              const double dist2 = (colors[i] - colors[j]).getNorm2();
              if (dist2 > maxAttributeDist2) {
                maxAttributeDist2 = dist2;
              }
            }
          }
          if (maxAttributeDist2 <= maxAttributeDist2Bwd) {
            for (size_t k = 0; k < 3; ++k) {
              centroid2[k] = 0;
            }
            if (params.useDistWeightedAvgBwd) {
              double sumWeights{0.0};
              for (int i = 0; i < colorsDists2.size(); ++i) {
                const double weight =
                  1 / (sqrt(colorsDists2[i].dist) + params.distOffsetBwd);
                for (size_t k = 0; k < 3; ++k) {
                  centroid2[k] += (colorsDists2[i].color[k] * weight);
                }
                sumWeights += weight;
              }
              centroid2 /= sumWeights;
            } else {
              for (auto& coldist : colorsDists2) {
                for (int k = 0; k < 3; ++k) {
                  centroid2[k] += coldist.color[k];
                }
              }
              centroid2 /= colorsDists2.size();
            }
            isDone = true;
          } else {
            colorsDists2.pop_back();
          }
        }
      }
    }
    double H = double(colorsDists2.size());
    double D2 = 0.0;
    for (const auto color2dist : colorsDists2) {
      auto color2 = color2dist.color;
      for (size_t k = 0; k < 3; ++k) {
        const double d2 = centroid2[k] - color2[k];
        D2 += d2 * d2;
      }
    }
    const double r = double(pointCountTarget) / double(pointCountSource);
    const double delta2 = (centroid2 - centroid1).getNorm2();
    const double eps = 0.000001;

    const bool fixWeight = 1;  // m42538
    if (!(fixWeight || delta2 > eps)) {
      // centroid2 == centroid1
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
471
472
      target.setColor(index, color1);
    } else {
473
474
475
476
477
478
479
480
481
482
483
484
485
486
      // centroid2 != centroid1
      double w = 0.0;

      if (!fixWeight) {
        const double alpha = D2 / delta2;
        const double a = H * r - 1.0;
        const double c = alpha * r - 1.0;
        if (fabs(a) < eps) {
          w = -0.5 * c;
        } else {
          const double delta = 1.0 - a * c;
          if (delta >= 0.0) {
            w = (-1.0 + sqrt(delta)) / a;
          }
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
487
488
        }
      }
489
490
      const double oneMinusW = 1.0 - w;
      Vec3<double> color0;
491
      for (size_t k = 0; k < 3; ++k) {
492
        color0[k] = PCCClip(
493
          round(w * centroid1[k] + oneMinusW * centroid2[k]), 0.0, clipMax[k]);
494
495
496
497
498
499
500
      }
      const double rSource = 1.0 / double(pointCountSource);
      const double rTarget = 1.0 / double(pointCountTarget);
      double minError = std::numeric_limits<double>::max();
      Vec3<double> bestColor(color0);
      Vec3<double> color;
      for (int32_t s1 = -params.searchRange; s1 <= params.searchRange; ++s1) {
501
        color[0] = PCCClip(color0[0] + s1, 0.0, clipMax[0]);
502
503
        for (int32_t s2 = -params.searchRange; s2 <= params.searchRange;
             ++s2) {
504
          color[1] = PCCClip(color0[1] + s2, 0.0, clipMax[1]);
505
506
          for (int32_t s3 = -params.searchRange; s3 <= params.searchRange;
               ++s3) {
507
            color[2] = PCCClip(color0[2] + s3, 0.0, clipMax[2]);
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532

            double e1 = 0.0;
            for (size_t k = 0; k < 3; ++k) {
              const double d = color[k] - color1[k];
              e1 += d * d;
            }
            e1 *= rTarget;

            double e2 = 0.0;
            for (const auto color2dist : colorsDists2) {
              auto color2 = color2dist.color;
              for (size_t k = 0; k < 3; ++k) {
                const double d = color[k] - color2[k];
                e2 += d * d;
              }
            }
            e2 *= rSource;

            const double error = std::max(e1, e2);
            if (error < minError) {
              minError = error;
              bestColor = color;
            }
          }
        }
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
533
      }
534
535
      target.setColor(
        index,
536
537
        Vec3<attr_t>(
          attr_t(bestColor[0]), attr_t(bestColor[1]), attr_t(bestColor[2])));
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
538
539
540
541
542
    }
  }
  return true;
}

543
544
//============================================================================
// Determine reflectance attribute values from a reference/source point cloud.
545
546
547
548
549
550
551
552
553
// For each point of the target p_t:
//  - Find the N_1 (1 < N_1) nearest neighbours in source to p_t and create
//    a set of points denoted by Ψ_1.
//  - Find the set of source points that p_t belongs to their set of N_2
//    nearest neighbours. Denote this set of points by Ψ_2.
//  - Compute the distance-weighted average of points in Ψ_1 and Ψ_2 by:
//        \bar{Ψ}_k = ∑_{q∈Ψ_k} c(q)/Δ(q,p_t)
//                    ----------------------- ,
//                    ∑_{q∈Ψ_k} 1/Δ(q,p_t)
554
//
555
556
557
558
// where Δ(a,b) denotes the Euclidian distance between the points a and b,
// and c(q) denotes the colour of point q.  Compute the average (or the
// weighted average with the number of points of each set as the weights)
// of \bar{Ψ}̅_1 and \bar{Ψ}̅_2 and transfer it to p_t.
559
560
561
562
563
//
// Differences in the scale and translation of the target and source point
// clouds, is handled according to:
//    posInTgt = (posInSrc - targetToSourceOffset) * sourceToTargetScaleFactor

564
bool
565
recolourReflectance(
566
  const AttributeDescription& attrDesc,
567
  const RecolourParams& cfg,
568
569
  const PCCPointSet3& source,
  double sourceToTargetScaleFactor,
570
  Vec3<double> targetToSourceOffset,
571
  PCCPointSet3& target)
572
{
573
574
  double targetToSourceScaleFactor = 1.0 / sourceToTargetScaleFactor;

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
575
576
577
578
579
  const size_t pointCountSource = source.getPointCount();
  const size_t pointCountTarget = target.getPointCount();
  if (!pointCountSource || !pointCountTarget || !source.hasReflectances()) {
    return false;
  }
580
581
582
583
  KDTreeVectorOfVectorsAdaptor<PCCPointSet3, double> kdtreeTarget(
    3, target, 10);
  KDTreeVectorOfVectorsAdaptor<PCCPointSet3, double> kdtreeSource(
    3, source, 10);
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
584
  target.addReflectances();
585
  std::vector<attr_t> refinedReflectances1;
586
587
  refinedReflectances1.resize(pointCountTarget);

588
589
  double clipMax = (1 << attrDesc.attr_bitdepth) - 1;

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
  double maxGeometryDist2Fwd = (cfg.maxGeometryDist2Fwd < 512)
    ? cfg.maxGeometryDist2Fwd
    : std::numeric_limits<double>::max();
  double maxGeometryDist2Bwd = (cfg.maxGeometryDist2Bwd < 512)
    ? cfg.maxGeometryDist2Bwd
    : std::numeric_limits<double>::max();
  double maxAttributeDist2Fwd = (cfg.maxAttributeDist2Fwd < 512)
    ? cfg.maxAttributeDist2Fwd
    : std::numeric_limits<double>::max();
  double maxAttributeDist2Bwd = (cfg.maxAttributeDist2Bwd < 512)
    ? cfg.maxAttributeDist2Bwd
    : std::numeric_limits<double>::max();

  // Forward direction
  const int num_resultsFwd = cfg.numNeighboursFwd;
  nanoflann::KNNResultSet<double> resultSetFwd(num_resultsFwd);
  std::vector<size_t> indicesFwd(num_resultsFwd);
  std::vector<double> sqrDistFwd(num_resultsFwd);
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
608
  for (size_t index = 0; index < pointCountTarget; ++index) {
609
    resultSetFwd.init(&indicesFwd[0], &sqrDistFwd[0]);
610

611
    Vec3<double> posInSrc =
612
613
      target[index] * targetToSourceScaleFactor + targetToSourceOffset;

614
    kdtreeSource.index->findNeighbors(
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
      resultSetFwd, &posInSrc[0], nanoflann::SearchParams(10));

    while (1) {
      if (indicesFwd.size() == 1)
        break;

      if (sqrDistFwd[int(resultSetFwd.size()) - 1] <= maxGeometryDist2Fwd)
        break;

      sqrDistFwd.pop_back();
      indicesFwd.pop_back();
    }

    bool isDone = false;
    if (cfg.skipAvgIfIdenticalSourcePointPresentFwd) {
      if (sqrDistFwd[0] < 0.0001) {
        refinedReflectances1[index] = source.getReflectance(indicesFwd[0]);
        isDone = true;
      }
    }

    if (isDone)
      continue;

    int nNN = indicesFwd.size();
    while (nNN > 0 && !isDone) {
      if (nNN == 1) {
        refinedReflectances1[index] = source.getReflectance(indicesFwd[0]);
        isDone = true;
        continue;
      }

647
      std::vector<attr_t> reflectances;
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
      reflectances.resize(0);
      reflectances.resize(nNN);
      for (int i = 0; i < nNN; ++i) {
        reflectances[i] = double(source.getReflectance(indicesFwd[i]));
      }
      double maxAttributeDist2 = std::numeric_limits<double>::min();
      for (int i = 0; i < nNN; ++i) {
        for (int j = 0; j < nNN; ++j) {
          const double dist2 = pow(reflectances[i] - reflectances[j], 2);
          if (dist2 > maxAttributeDist2)
            maxAttributeDist2 = dist2;
        }
      }
      if (maxAttributeDist2 > maxAttributeDist2Fwd) {
        --nNN;
      } else {
        double refinedReflectance = 0.0;
        if (cfg.useDistWeightedAvgFwd) {
          double sumWeights{0.0};
          for (int i = 0; i < nNN; ++i) {
            const double weight = 1 / (sqrDistFwd[i] + cfg.distOffsetFwd);
            refinedReflectance +=
              source.getReflectance(indicesFwd[i]) * weight;
            sumWeights += weight;
          }
          refinedReflectance /= sumWeights;
        } else {
          for (int i = 0; i < nNN; ++i)
            refinedReflectance += source.getReflectance(indicesFwd[i]);
          refinedReflectance /= nNN;
        }
        refinedReflectances1[index] =
680
          attr_t(PCCClip(round(refinedReflectance), 0.0, clipMax));
681
682
683
        isDone = true;
      }
    }
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
684
  }
685

686
687
688
689
690
691
692
693
  // Backward direction
  const size_t num_resultsBwd = cfg.numNeighboursBwd;
  std::vector<size_t> indicesBwd(num_resultsBwd);
  std::vector<double> sqrDistBwd(num_resultsBwd);
  nanoflann::KNNResultSet<double> resultSetBwd(num_resultsBwd);

  struct DistReflectance {
    double dist;
694
    attr_t reflectance;
695
696
697
698
  };
  std::vector<std::vector<DistReflectance>> refinedReflectancesDists2;
  refinedReflectancesDists2.resize(pointCountTarget);

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
699
  for (size_t index = 0; index < pointCountSource; ++index) {
700
    const attr_t reflectance = source.getReflectance(index);
701
    resultSetBwd.init(&indicesBwd[0], &sqrDistBwd[0]);
702

703
    Vec3<double> posInTgt =
704
705
      (source[index] - targetToSourceOffset) * sourceToTargetScaleFactor;

706
    kdtreeTarget.index->findNeighbors(
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
      resultSetBwd, &posInTgt[0], nanoflann::SearchParams(10));

    for (int i = 0; i < num_resultsBwd; ++i) {
      if (sqrDistBwd[i] <= maxGeometryDist2Bwd) {
        refinedReflectancesDists2[indicesBwd[i]].push_back(
          DistReflectance{sqrDistBwd[i], reflectance});
      }
    }
  }

  for (size_t index = 0; index < pointCountTarget; ++index) {
    std::sort(
      refinedReflectancesDists2[index].begin(),
      refinedReflectancesDists2[index].end(),
      [](DistReflectance& dc1, DistReflectance& dc2) {
        return dc1.dist < dc2.dist;
      });
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
724
  }
725

Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
726
  for (size_t index = 0; index < pointCountTarget; ++index) {
727
    const attr_t reflectance1 = refinedReflectances1[index];
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
    auto& reflectancesDists2 = refinedReflectancesDists2[index];
    if (reflectancesDists2.empty()) {
      target.setReflectance(index, reflectance1);
      continue;
    }

    bool isDone = false;
    const double centroid1 = reflectance1;
    double centroid2 = 0.0;
    if (cfg.skipAvgIfIdenticalSourcePointPresentBwd) {
      if (reflectancesDists2[0].dist < 0.0001) {
        auto temp = reflectancesDists2[0];
        reflectancesDists2.clear();
        reflectancesDists2.push_back(temp);
        centroid2 = reflectancesDists2[0].reflectance;
        isDone = true;
      }
    }
    if (!isDone) {
      int nNN = reflectancesDists2.size();
      while (nNN > 0 && !isDone) {
        nNN = reflectancesDists2.size();
        if (nNN == 1) {
          auto temp = reflectancesDists2[0];
          reflectancesDists2.clear();
          reflectancesDists2.push_back(temp);
          centroid2 = reflectancesDists2[0].reflectance;
          isDone = true;
        }
        if (!isDone) {
          std::vector<double> reflectances;
          reflectances.resize(0);
          reflectances.resize(nNN);
          for (int i = 0; i < nNN; ++i) {
            reflectances[i] = double(reflectancesDists2[i].reflectance);
          }
          double maxAttributeDist2 = std::numeric_limits<double>::min();
          for (int i = 0; i < nNN; ++i) {
            for (int j = 0; j < nNN; ++j) {
              const double dist2 = pow(reflectances[i] - reflectances[j], 2);
              if (dist2 > maxAttributeDist2) {
                maxAttributeDist2 = dist2;
              }
            }
          }
          if (maxAttributeDist2 <= maxAttributeDist2Bwd) {
            centroid2 = 0;
            if (cfg.useDistWeightedAvgBwd) {
              double sumWeights{0.0};
              for (int i = 0; i < reflectancesDists2.size(); ++i) {
                const double weight =
                  1 / (sqrt(reflectancesDists2[i].dist) + cfg.distOffsetBwd);
                centroid2 += (reflectancesDists2[i].reflectance * weight);
                sumWeights += weight;
              }
              centroid2 /= sumWeights;
            } else {
              for (auto& refdist : reflectancesDists2) {
                centroid2 += refdist.reflectance;
              }
              centroid2 /= reflectancesDists2.size();
            }
            isDone = true;
          } else {
            reflectancesDists2.pop_back();
          }
        }
      }
    }
    double H = double(reflectancesDists2.size());
    double D2 = 0.0;
    for (const auto reflectance2dist : reflectancesDists2) {
      auto reflectance2 = reflectance2dist.reflectance;
      const double d2 = centroid2 - reflectance2;
      D2 += d2 * d2;
    }
    const double r = double(pointCountTarget) / double(pointCountSource);
    const double delta2 = pow(centroid2 - centroid1, 2);
    const double eps = 0.000001;

    const bool fixWeight = 1;  // m42538
    if (!(fixWeight || delta2 > eps)) {
      // centroid2 == centroid1
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
811
812
      target.setReflectance(index, reflectance1);
    } else {
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
      // centroid2 != centroid1
      double w = 0.0;

      if (!fixWeight) {
        const double alpha = D2 / delta2;
        const double a = H * r - 1.0;
        const double c = alpha * r - 1.0;
        if (fabs(a) < eps) {
          w = -0.5 * c;
        } else {
          const double delta = 1.0 - a * c;
          if (delta >= 0.0) {
            w = (-1.0 + sqrt(delta)) / a;
          }
        }
      }
      const double oneMinusW = 1.0 - w;
      double reflectance0;
      reflectance0 =
832
        PCCClip(round(w * centroid1 + oneMinusW * centroid2), 0.0, clipMax);
833
834
835
836
837
838
      const double rSource = 1.0 / double(pointCountSource);
      const double rTarget = 1.0 / double(pointCountTarget);
      double minError = std::numeric_limits<double>::max();
      double bestReflectance = reflectance0;
      double reflectance;
      for (int32_t s1 = -cfg.searchRange; s1 <= cfg.searchRange; ++s1) {
839
        reflectance = PCCClip(reflectance0 + s1, 0.0, clipMax);
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
        double e1 = 0.0;
        const double d = reflectance - reflectance1;
        e1 += d * d;
        e1 *= rTarget;

        double e2 = 0.0;
        for (const auto reflectance2dist : reflectancesDists2) {
          auto reflectance2 = reflectance2dist.reflectance;
          const double d = reflectance - reflectance2;
          e2 += d * d;
        }
        e2 *= rSource;

        const double error = std::max(e1, e2);
        if (error < minError) {
          minError = error;
          bestReflectance = reflectance;
        }
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
858
      }
859
      target.setReflectance(index, attr_t(bestReflectance));
Khaled Mammou's avatar
TMC3v0    
Khaled Mammou committed
860
861
862
863
    }
  }
  return true;
}
864
865

//============================================================================
866
// Recolour an attribute based on a source/reference point cloud.
867
868
869
//
// Differences in the scale and translation of the target and source point
// clouds, is handled according to:
870
871
//   posInTgt =
//     (posInSrc - targetToSourceOffset) * sourceToTargetScaleFactor - offset
872

873
int
874
recolour(
875
  const AttributeDescription& desc,
876
  const RecolourParams& cfg,
877
878
  const PCCPointSet3& source,
  float sourceToTargetScaleFactor,
879
880
  Vec3<int> targetToSourceOffset,
  Vec3<int> offset,
881
882
  PCCPointSet3* target)
{
883
  Vec3<double> combinedOffset;
884
  for (int k = 0; k < 3; k++)
885
886
    combinedOffset[k] =
      targetToSourceOffset[k] + double(offset[k]) / sourceToTargetScaleFactor;
887

888
889
890
  // todo(df): fix the incorrect assumption here that 3-component
  // attributes are colour (and that single components are reflectance)
  if (desc.attributeLabel == KnownAttributeLabel::kColour) {
891
    bool ok = recolourColour(
892
      desc, cfg, source, sourceToTargetScaleFactor, combinedOffset, *target);
893
894
895
896
897
898
899

    if (!ok) {
      std::cout << "Error: can't transfer colors!" << std::endl;
      return -1;
    }
  }

900
  if (desc.attributeLabel == KnownAttributeLabel::kReflectance) {
901
    bool ok = recolourReflectance(
902
      desc, cfg, source, sourceToTargetScaleFactor, combinedOffset, *target);
903
904
905
906
907
908
909
910
911
912
913
914

    if (!ok) {
      std::cout << "Error: can't transfer reflectance!" << std::endl;
      return -1;
    }
  }

  return 0;
}

//============================================================================

915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
void
convertGbrToYCbCrBt709(PCCPointSet3& cloud)
{
  for (int i = 0; i < cloud.getPointCount(); i++) {
    auto& val = cloud.getColor(i);
    val = transformGbrToYCbCrBt709(val);
  }
}

//============================================================================

void
convertYCbCrBt709ToGbr(PCCPointSet3& cloud)
{
  for (int i = 0; i < cloud.getPointCount(); i++) {
    auto& val = cloud.getColor(i);
    val = transformYCbCrBt709ToGbr(val);
  }
}

//============================================================================

937
}  // namespace pcc