libvisiontransfer  7.1.0
reconstruct3d.cpp
1 /*******************************************************************************
2  * Copyright (c) 2019 Nerian Vision GmbH
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *******************************************************************************/
14 
15 #include "reconstruct3d.h"
16 #include "visiontransfer/alignedallocator.h"
17 #include <vector>
18 #include <cstring>
19 #include <algorithm>
20 #include <fstream>
21 #include <stdexcept>
22 #include <cmath>
23 
24 // SIMD Headers
25 #ifdef __AVX2__
26 #include <immintrin.h>
27 #elif __SSE2__
28 #include <emmintrin.h>
29 #endif
30 
31 using namespace std;
32 using namespace visiontransfer;
33 using namespace visiontransfer::internal;
34 
35 namespace visiontransfer {
36 
37 /*************** Pimpl class containing all private members ***********/
38 
39 class Reconstruct3D::Pimpl {
40 public:
41  Pimpl();
42 
43  float* createPointMap(const unsigned short* dispMap, int width, int height,
44  int rowStride, const float* q, unsigned short minDisparity);
45 
46  float* createPointMap(const ImagePair& imagePair, unsigned short minDisparity);
47 
48  void projectSinglePoint(int imageX, int imageY, unsigned short disparity, const float* q,
49  float& pointX, float& pointY, float& pointZ);
50 
51  void writePlyFile(const char* file, const unsigned short* dispMap,
52  const unsigned char* image, int width, int height, ImagePair::ImageFormat format,
53  int dispRowStride, int imageRowStride, const float* q,
54  double maxZ, bool binary);
55 
56  void writePlyFile(const char* file, const ImagePair& imagePair,
57  double maxZ, bool binary);
58 
59 private:
60  std::vector<float, AlignedAllocator<float> > pointMap;
61 
62  float* createPointMapFallback(const unsigned short* dispMap, int width, int height,
63  int rowStride, const float* q, unsigned short minDisparity);
64 
65  float* createPointMapSSE2(const unsigned short* dispMap, int width, int height,
66  int rowStride, const float* q, unsigned short minDisparity);
67 
68  float* createPointMapAVX2(const unsigned short* dispMap, int width, int height,
69  int rowStride, const float* q, unsigned short minDisparity);
70 };
71 
72 /******************** Stubs for all public members ********************/
73 
74 Reconstruct3D::Reconstruct3D()
75  :pimpl(new Pimpl) {
76 }
77 
78 Reconstruct3D::~Reconstruct3D() {
79  delete pimpl;
80 }
81 
82 float* Reconstruct3D::createPointMap(const unsigned short* dispMap, int width, int height,
83  int rowStride, const float* q, unsigned short minDisparity) {
84  return pimpl->createPointMap(dispMap, width, height, rowStride, q, minDisparity);
85 }
86 
87 float* Reconstruct3D::createPointMap(const ImagePair& imagePair, unsigned short minDisparity) {
88  return pimpl->createPointMap(imagePair, minDisparity);
89 }
90 
91 void Reconstruct3D::projectSinglePoint(int imageX, int imageY, unsigned short disparity,
92  const float* q, float& pointX, float& pointY, float& pointZ) {
93  pimpl->projectSinglePoint(imageX, imageY, disparity, q, pointX, pointY, pointZ);
94 }
95 
96 void Reconstruct3D::writePlyFile(const char* file, const unsigned short* dispMap,
97  const unsigned char* image, int width, int height, ImagePair::ImageFormat format, int dispRowStride,
98  int imageRowStride, const float* q, double maxZ, bool binary) {
99  pimpl->writePlyFile(file, dispMap, image, width, height, format, dispRowStride,
100  imageRowStride, q, maxZ, binary);
101 }
102 
103 void Reconstruct3D::writePlyFile(const char* file, const ImagePair& imagePair,
104  double maxZ, bool binary) {
105  pimpl->writePlyFile(file, imagePair, maxZ, binary);
106 }
107 
108 /******************** Implementation in pimpl class *******************/
109 
110 Reconstruct3D::Pimpl::Pimpl() {
111 }
112 
113 float* Reconstruct3D::Pimpl::createPointMap(const unsigned short* dispMap, int width,
114  int height, int rowStride, const float* q, unsigned short minDisparity) {
115 
116  // Allocate the buffer
117  if(pointMap.size() != static_cast<unsigned int>(4*width*height)) {
118  pointMap.resize(4*width*height);
119  }
120 
121 # ifdef __AVX2__
122  return createPointMapAVX2(dispMap, width, height, rowStride, q, minDisparity);
123 # elif __SSE2__
124  return createPointMapSSE2(dispMap, width, height, rowStride, q, minDisparity);
125 # else
126  return createPointMapFallback(dispMap, width, height, rowStride, q, minDisparity);
127 # endif
128 }
129 
130 float* Reconstruct3D::Pimpl::createPointMap(const ImagePair& imagePair, unsigned short minDisparity) {
131  if(imagePair.getPixelFormat(1) != ImagePair::FORMAT_12_BIT_MONO) {
132  throw std::runtime_error("Disparity map must have 12-bit pixel format!");
133  }
134 
135  return createPointMap(reinterpret_cast<unsigned short*>(imagePair.getPixelData(1)), imagePair.getWidth(),
136  imagePair.getHeight(), imagePair.getRowStride(1), imagePair.getQMatrix(), minDisparity);
137 }
138 
139 float* Reconstruct3D::Pimpl::createPointMapFallback(const unsigned short* dispMap, int width,
140  int height, int rowStride, const float* q, unsigned short minDisparity) {
141  // Code without SSE or AVX optimization
142  float* outputPtr = &pointMap[0];
143  int stride = rowStride / 2;
144 
145  for(int y = 0; y < height; y++) {
146  double qx = q[1]*y + q[3];
147  double qy = q[5]*y + q[7];
148  double qz = q[9]*y + q[11];
149  double qw = q[13]*y + q[15];
150 
151  for(int x = 0; x < width; x++) {
152  unsigned short intDisp = std::max(minDisparity, dispMap[y*stride + x]);
153  if(intDisp >= 0xFFF) {
154  intDisp = minDisparity; // Invalid disparity
155  }
156 
157  double d = intDisp / 16.0;
158  double w = qw + q[14]*d;
159 
160  *outputPtr = static_cast<float>((qx + q[2]*d)/w); // x
161  outputPtr++;
162 
163  *outputPtr = static_cast<float>((qy + q[6]*d)/w); // y
164  outputPtr++;
165 
166  *outputPtr = static_cast<float>((qz + q[10]*d)/w); // z
167  outputPtr+=2; // Consider padding
168 
169  qx += q[0];
170  qy += q[4];
171  qz += q[8];
172  qw += q[12];
173  }
174  }
175  return &pointMap[0];
176 }
177 
178 void Reconstruct3D::Pimpl::projectSinglePoint(int imageX, int imageY, unsigned short disparity,
179  const float* q, float& pointX, float& pointY, float& pointZ) {
180 
181  double d = disparity / 16.0;
182  double w = q[15] + q[14]*d;
183  pointX = static_cast<float>((imageX*q[0] + q[3])/w);
184  pointY = static_cast<float>((imageY*q[5] + q[7])/w);
185  pointZ = static_cast<float>(q[11]/w);
186 }
187 
188 # ifdef __AVX2__
189 float* Reconstruct3D::Pimpl::createPointMapAVX2(const unsigned short* dispMap, int width,
190  int height, int rowStride, const float* q, unsigned short minDisparity) {
191 
192  // Create column vectors of q
193  const __m256 qCol0 = _mm256_setr_ps(q[0], q[4], q[8], q[12], q[0], q[4], q[8], q[12]);
194  const __m256 qCol1 = _mm256_setr_ps(q[1], q[5], q[9], q[13], q[1], q[5], q[9], q[13]);
195  const __m256 qCol2 = _mm256_setr_ps(q[2], q[6], q[10], q[14], q[2], q[6], q[10], q[14]);
196  const __m256 qCol3 = _mm256_setr_ps(q[3], q[7], q[11], q[15], q[3], q[7], q[11], q[15]);
197 
198  // More constants that we need
199  const __m256i minDispVector = _mm256_set1_epi16(minDisparity);
200  const __m256i maxDispVector = _mm256_set1_epi16(0xFFF);
201  const __m256 scaleVector = _mm256_set1_ps(1.0/16.0);
202  const __m256i zeroVector = _mm256_set1_epi16(0);
203 
204  float* outputPtr = &pointMap[0];
205 
206  for(int y = 0; y < height; y++) {
207  const unsigned char* rowStart = &reinterpret_cast<const unsigned char*>(dispMap)[y*rowStride];
208  const unsigned char* rowEnd = &reinterpret_cast<const unsigned char*>(dispMap)[y*rowStride + 2*width];
209 
210  int x = 0;
211  for(const unsigned char* ptr = rowStart; ptr != rowEnd; ptr += 32) {
212  __m256i disparities = _mm256_load_si256(reinterpret_cast<const __m256i*>(ptr));
213 
214  // Find invalid disparities and set them to 0
215  __m256i validMask = _mm256_cmpgt_epi16(maxDispVector, disparities);
216  disparities = _mm256_and_si256(validMask, disparities);
217 
218  // Clamp to minimum disparity
219  disparities = _mm256_max_epi16(disparities, minDispVector);
220 
221  // Stupid AVX2 unpack mixes everything up! Lets swap the register beforehand.
222  __m256i disparitiesMixup = _mm256_permute4x64_epi64(disparities, 0xd8);
223 
224  // Convert to floats and scale with 1/16
225  __m256 floatDisp = _mm256_cvtepi32_ps(_mm256_unpacklo_epi16(disparitiesMixup, zeroVector));
226  __m256 dispScaled = _mm256_mul_ps(floatDisp, scaleVector);
227 
228  // Copy to array
229 #ifdef _MSC_VER
230  __declspec(align(32)) float dispArray[16];
231 #else
232  float dispArray[16]__attribute__((aligned(32)));
233 #endif
234  _mm256_store_ps(&dispArray[0], dispScaled);
235 
236  // Same for other half
237  floatDisp = _mm256_cvtepi32_ps(_mm256_unpackhi_epi16(disparitiesMixup, zeroVector));
238  dispScaled = _mm256_mul_ps(floatDisp, scaleVector);
239  _mm256_store_ps(&dispArray[8], dispScaled);
240 
241  // Iterate over disparities and perform matrix multiplication for each
242  for(int i=0; i<16; i+=2) {
243  // Create two vectors
244  __m256 vec = _mm256_setr_ps(x, y, dispArray[i], 1.0,
245  x+1, y, dispArray[i+1], 1.0);
246 
247  // Multiply with matrix
248  __m256 u1 = _mm256_shuffle_ps(vec,vec, _MM_SHUFFLE(0,0,0,0));
249  __m256 u2 = _mm256_shuffle_ps(vec,vec, _MM_SHUFFLE(1,1,1,1));
250  __m256 u3 = _mm256_shuffle_ps(vec,vec, _MM_SHUFFLE(2,2,2,2));
251  __m256 u4 = _mm256_shuffle_ps(vec,vec, _MM_SHUFFLE(3,3,3,3));
252 
253  __m256 prod1 = _mm256_mul_ps(u1, qCol0);
254  __m256 prod2 = _mm256_mul_ps(u2, qCol1);
255  __m256 prod3 = _mm256_mul_ps(u3, qCol2);
256  __m256 prod4 = _mm256_mul_ps(u4, qCol3);
257 
258  __m256 multResult = _mm256_add_ps(_mm256_add_ps(prod1, prod2), _mm256_add_ps(prod3, prod4));
259 
260  // Divide by w to receive point coordinates
261  __m256 point = _mm256_div_ps(multResult,
262  _mm256_shuffle_ps(multResult,multResult, _MM_SHUFFLE(3,3,3,3)));
263 
264  // Write result to memory
265  _mm256_store_ps(outputPtr, point);
266 
267  outputPtr += 8;
268  x+=2;
269  }
270  }
271  }
272 
273  return &pointMap[0];
274 }
275 #endif
276 
277 #ifdef __SSE2__
278 float* Reconstruct3D::Pimpl::createPointMapSSE2(const unsigned short* dispMap, int width,
279  int height, int rowStride, const float* q, unsigned short minDisparity) {
280 
281  // Create column vectors of q
282  const __m128 qCol0 = _mm_setr_ps(q[0], q[4], q[8], q[12]);
283  const __m128 qCol1 = _mm_setr_ps(q[1], q[5], q[9], q[13]);
284  const __m128 qCol2 = _mm_setr_ps(q[2], q[6], q[10], q[14]);
285  const __m128 qCol3 = _mm_setr_ps(q[3], q[7], q[11], q[15]);
286 
287  // More constants that we need
288  const __m128i minDispVector = _mm_set1_epi16(minDisparity);
289  const __m128i maxDispVector = _mm_set1_epi16(0xFFF);
290  const __m128 scaleVector = _mm_set1_ps(1.0/16.0);
291  const __m128i zeroVector = _mm_set1_epi16(0);
292 
293  float* outputPtr = &pointMap[0];
294 
295  for(int y = 0; y < height; y++) {
296  const unsigned char* rowStart = &reinterpret_cast<const unsigned char*>(dispMap)[y*rowStride];
297  const unsigned char* rowEnd = &reinterpret_cast<const unsigned char*>(dispMap)[y*rowStride + 2*width];
298 
299  int x = 0;
300  for(const unsigned char* ptr = rowStart; ptr != rowEnd; ptr += 16) {
301  __m128i disparities = _mm_load_si128(reinterpret_cast<const __m128i*>(ptr));
302 
303  // Find invalid disparities and set them to 0
304  __m128i validMask = _mm_cmplt_epi16(disparities, maxDispVector);
305  disparities = _mm_and_si128(validMask, disparities);
306 
307  // Clamp to minimum disparity
308  disparities = _mm_max_epi16(disparities, minDispVector);
309 
310  // Convert to floats and scale with 1/16
311  __m128 floatDisp = _mm_cvtepi32_ps(_mm_unpacklo_epi16(disparities, zeroVector));
312  __m128 dispScaled = _mm_mul_ps(floatDisp, scaleVector);
313 
314  // Copy to array
315 #ifdef _MSC_VER
316  __declspec(align(16)) float dispArray[8];
317 #else
318  float dispArray[8]__attribute__((aligned(16)));
319 #endif
320  _mm_store_ps(&dispArray[0], dispScaled);
321 
322  // Same for other half
323  floatDisp = _mm_cvtepi32_ps(_mm_unpackhi_epi16(disparities, zeroVector));
324  dispScaled = _mm_mul_ps(floatDisp, scaleVector);
325  _mm_store_ps(&dispArray[4], dispScaled);
326 
327  // Iterate over disparities and perform matrix multiplication for each
328  for(int i=0; i<8; i++) {
329  // Create vector
330  __m128 vec = _mm_setr_ps(static_cast<float>(x), static_cast<float>(y), dispArray[i], 1.0);
331 
332  // Multiply with matrix
333  __m128 u1 = _mm_shuffle_ps(vec,vec, _MM_SHUFFLE(0,0,0,0));
334  __m128 u2 = _mm_shuffle_ps(vec,vec, _MM_SHUFFLE(1,1,1,1));
335  __m128 u3 = _mm_shuffle_ps(vec,vec, _MM_SHUFFLE(2,2,2,2));
336  __m128 u4 = _mm_shuffle_ps(vec,vec, _MM_SHUFFLE(3,3,3,3));
337 
338  __m128 prod1 = _mm_mul_ps(u1, qCol0);
339  __m128 prod2 = _mm_mul_ps(u2, qCol1);
340  __m128 prod3 = _mm_mul_ps(u3, qCol2);
341  __m128 prod4 = _mm_mul_ps(u4, qCol3);
342 
343  __m128 multResult = _mm_add_ps(_mm_add_ps(prod1, prod2), _mm_add_ps(prod3, prod4));
344 
345  // Divide by w to receive point coordinates
346  __m128 point = _mm_div_ps(multResult,
347  _mm_shuffle_ps(multResult,multResult, _MM_SHUFFLE(3,3,3,3)));
348 
349  // Write result to memory
350  _mm_store_ps(outputPtr, point);
351 
352  outputPtr += 4;
353  x++;
354  }
355  }
356  }
357 
358  return &pointMap[0];
359 }
360 #endif
361 
362 void Reconstruct3D::Pimpl::writePlyFile(const char* file, const unsigned short* dispMap,
363  const unsigned char* image, int width, int height, ImagePair::ImageFormat format, int dispRowStride,
364  int imageRowStride, const float* q, double maxZ, bool binary) {
365 
366  float* pointMap = createPointMap(dispMap, width, height, dispRowStride, q, 0);
367 
368  // Count number of valid points
369  int pointsCount = 0;
370  if(maxZ >= 0) {
371  for(int i=0; i<width*height; i++) {
372  if(pointMap[4*i+2] <= maxZ) {
373  pointsCount++;
374  }
375  }
376  } else {
377  pointsCount = width*height;
378  }
379 
380  // Write file header
381  fstream strm(file, binary ? (ios::out | ios::binary) : ios::out);
382  strm << "ply" << endl;
383 
384  if(binary) {
385  strm << "format binary_little_endian 1.0" << endl;
386  } else {
387  strm << "format ascii 1.0" << endl;
388  }
389 
390  strm << "element vertex " << pointsCount << endl
391  << "property float x" << endl
392  << "property float y" << endl
393  << "property float z" << endl
394  << "property uchar red" << endl
395  << "property uchar green" << endl
396  << "property uchar blue" << endl
397  << "end_header" << endl;
398 
399  // Write points
400  for(int i=0; i<width*height; i++) {
401  int y = i / width;
402  int x = i % width;
403 
404  if(maxZ < 0 || pointMap[4*i+2] <= maxZ) {
405  if(binary) {
406  // Write binary format
407  strm.write(reinterpret_cast<char*>(&pointMap[4*i]), sizeof(float)*3);
408  if(format == ImagePair::FORMAT_8_BIT_RGB) {
409  const unsigned char* col = &image[y*imageRowStride + 3*x];
410  strm.write(reinterpret_cast<const char*>(col), 3*sizeof(*col));
411  } else if(format == ImagePair::FORMAT_8_BIT_MONO) {
412  const unsigned char* col = &image[y*imageRowStride + x];
413  unsigned char writeData[3] = {*col, *col, *col};
414  strm.write(reinterpret_cast<const char*>(writeData), sizeof(writeData));
415  } else if(format == ImagePair::FORMAT_12_BIT_MONO) {
416  const unsigned short* col = reinterpret_cast<const unsigned short*>(&image[y*imageRowStride + 2*x]);
417  unsigned char writeData[3] = {
418  (unsigned char)(*col >> 4),
419  (unsigned char)(*col >> 4),
420  (unsigned char)(*col >> 4)
421  };
422  strm.write(reinterpret_cast<const char*>(writeData), sizeof(writeData));
423  }
424  } else {
425  // Write ASCII format
426  if(std::isfinite(pointMap[4*i + 2])) {
427  strm << pointMap[4*i]
428  << " " << pointMap[4*i + 1]
429  << " " << pointMap[4*i + 2];
430  } else {
431  strm << "NaN NaN NaN";
432  }
433 
434  if(format == ImagePair::FORMAT_8_BIT_RGB) {
435  const unsigned char* col = &image[y*imageRowStride + 3*x];
436  strm << " " << static_cast<int>(col[0])
437  << " " << static_cast<int>(col[1])
438  << " " << static_cast<int>(col[2]) << endl;
439  } else if(format == ImagePair::FORMAT_8_BIT_MONO) {
440  const unsigned char* col = &image[y*imageRowStride + x];
441  strm << " " << static_cast<int>(*col)
442  << " " << static_cast<int>(*col)
443  << " " << static_cast<int>(*col) << endl;
444  } else if(format == ImagePair::FORMAT_12_BIT_MONO) {
445  const unsigned short* col = reinterpret_cast<const unsigned short*>(&image[y*imageRowStride + 2*x]);
446  strm << " " << static_cast<int>(*col >> 4)
447  << " " << static_cast<int>(*col >> 4)
448  << " " << static_cast<int>(*col >> 4) << endl;
449  }
450  }
451  }
452  }
453 }
454 
455 void Reconstruct3D::Pimpl::writePlyFile(const char* file, const ImagePair& imagePair,
456  double maxZ, bool binary) {
457  if(imagePair.getPixelFormat(1) != ImagePair::FORMAT_12_BIT_MONO) {
458  throw std::runtime_error("Disparity map must have 12-bit pixel format!");
459  }
460 
461  writePlyFile(file, reinterpret_cast<unsigned short*>(imagePair.getPixelData(1)),
462  imagePair.getPixelData(0), imagePair.getWidth(), imagePair.getHeight(),
463  imagePair.getPixelFormat(0),
464  imagePair.getRowStride(1), imagePair.getRowStride(0), imagePair.getQMatrix(),
465  maxZ, binary);
466 }
467 
468 } // namespace
469 
int getHeight() const
Returns the height of each image.
Definition: imagepair.h:187
void writePlyFile(const char *file, const unsigned short *dispMap, const unsigned char *image, int width, int height, ImagePair::ImageFormat format, int dispRowStride, int imageRowStride, const float *q, double maxZ=std::numeric_limits< double >::max(), bool binary=false)
Projects the given disparity map to 3D points and exports the result to a PLY file.
ImageFormat getPixelFormat(int imageNumber) const
Returns the pixel format for the given image.
Definition: imagepair.h:206
int getRowStride(int imageNumber) const
Returns the row stride for the pixel data of one image.
Definition: imagepair.h:195
ImageFormat
Image formats that can be transferred.
Definition: imagepair.h:38
const float * getQMatrix() const
Returns a pointer to the disparity-to-depth mapping matrix q.
Definition: imagepair.h:225
int getWidth() const
Returns the width of each image.
Definition: imagepair.h:182
void projectSinglePoint(int imageX, int imageY, unsigned short disparity, const float *q, float &pointX, float &pointY, float &pointZ)
Reconstructs the 3D location of one individual point.
unsigned char * getPixelData(int imageNumber) const
Returns the pixel data for the given image.
Definition: imagepair.h:217
float * createPointMap(const unsigned short *dispMap, int width, int height, int rowStride, const float *q, unsigned short minDisparity=1)
Reconstructs the 3D location of each pixel in the given disparity map.
A set of two images, which are usually the left camera image and the disparity map.
Definition: imagepair.h:33
Nerian Vision Technologies