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