pointcloud.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2015, OpenCV Foundation, all rights reserved.
  14. // Third party copyrights are property of their respective owners.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification,
  17. // are permitted provided that the following conditions are met:
  18. //
  19. // * Redistribution's of source code must retain the above copyright notice,
  20. // this list of conditions and the following disclaimer.
  21. //
  22. // * Redistribution's in binary form must reproduce the above copyright notice,
  23. // this list of conditions and the following disclaimer in the documentation
  24. // and/or other materials provided with the distribution.
  25. //
  26. // * The name of the copyright holders may not be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. //
  29. // This software is provided by the copyright holders and contributors "as is" and
  30. // any express or implied warranties, including, but not limited to, the implied
  31. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. // In no event shall the Intel Corporation or contributors be liable for any direct,
  33. // indirect, incidental, special, exemplary, or consequential damages
  34. // (including, but not limited to, procurement of substitute goods or services;
  35. // loss of use, data, or profits; or business interruption) however caused
  36. // and on any theory of liability, whether in contract, strict liability,
  37. // or tort (including negligence or otherwise) arising in any way out of
  38. // the use of this software, even if advised of the possibility of such damage.
  39. //
  40. //M*/
  41. #include <iostream>
  42. #include <opencv2/core.hpp>
  43. #include <opencv2/highgui.hpp>
  44. #include <opencv2/calib3d.hpp>
  45. #include <opencv2/imgproc.hpp>
  46. #include <opencv2/structured_light.hpp>
  47. #include <opencv2/opencv_modules.hpp>
  48. // (if you did not build the opencv_viz module, you will only see the disparity images)
  49. #ifdef HAVE_OPENCV_VIZ
  50. #include <opencv2/viz.hpp>
  51. #endif
  52. using namespace std;
  53. using namespace cv;
  54. static const char* keys =
  55. { "{@images_list | | Image list where the captured pattern images are saved}"
  56. "{@calib_param_path | | Calibration_parameters }"
  57. "{@proj_width | | The projector width used to acquire the pattern }"
  58. "{@proj_height | | The projector height used to acquire the pattern}"
  59. "{@white_thresh | | The white threshold height (optional)}"
  60. "{@black_thresh | | The black threshold (optional)}" };
  61. static void help()
  62. {
  63. cout << "\nThis example shows how to use the \"Structured Light module\" to decode a previously acquired gray code pattern, generating a pointcloud"
  64. "\nCall:\n"
  65. "./example_structured_light_pointcloud <images_list> <calib_param_path> <proj_width> <proj_height> <white_thresh> <black_thresh>\n"
  66. << endl;
  67. }
  68. static bool readStringList( const string& filename, vector<string>& l )
  69. {
  70. l.resize( 0 );
  71. FileStorage fs( filename, FileStorage::READ );
  72. if( !fs.isOpened() )
  73. {
  74. cerr << "failed to open " << filename << endl;
  75. return false;
  76. }
  77. FileNode n = fs.getFirstTopLevelNode();
  78. if( n.type() != FileNode::SEQ )
  79. {
  80. cerr << "cam 1 images are not a sequence! FAIL" << endl;
  81. return false;
  82. }
  83. FileNodeIterator it = n.begin(), it_end = n.end();
  84. for( ; it != it_end; ++it )
  85. {
  86. l.push_back( ( string ) *it );
  87. }
  88. n = fs["cam2"];
  89. if( n.type() != FileNode::SEQ )
  90. {
  91. cerr << "cam 2 images are not a sequence! FAIL" << endl;
  92. return false;
  93. }
  94. it = n.begin(), it_end = n.end();
  95. for( ; it != it_end; ++it )
  96. {
  97. l.push_back( ( string ) *it );
  98. }
  99. if( l.size() % 2 != 0 )
  100. {
  101. cout << "Error: the image list contains odd (non-even) number of elements\n";
  102. return false;
  103. }
  104. return true;
  105. }
  106. int main( int argc, char** argv )
  107. {
  108. structured_light::GrayCodePattern::Params params;
  109. CommandLineParser parser( argc, argv, keys );
  110. String images_file = parser.get<String>( 0 );
  111. String calib_file = parser.get<String>( 1 );
  112. params.width = parser.get<int>( 2 );
  113. params.height = parser.get<int>( 3 );
  114. if( images_file.empty() || calib_file.empty() || params.width < 1 || params.height < 1 || argc < 5 || argc > 7 )
  115. {
  116. help();
  117. return -1;
  118. }
  119. // Set up GraycodePattern with params
  120. Ptr<structured_light::GrayCodePattern> graycode = structured_light::GrayCodePattern::create( params );
  121. size_t white_thresh = 0;
  122. size_t black_thresh = 0;
  123. if( argc == 7 )
  124. {
  125. // If passed, setting the white and black threshold, otherwise using default values
  126. white_thresh = parser.get<unsigned>( 4 );
  127. black_thresh = parser.get<unsigned>( 5 );
  128. graycode->setWhiteThreshold( white_thresh );
  129. graycode->setBlackThreshold( black_thresh );
  130. }
  131. vector<string> imagelist;
  132. bool ok = readStringList( images_file, imagelist );
  133. if( !ok || imagelist.empty() )
  134. {
  135. cout << "can not open " << images_file << " or the string list is empty" << endl;
  136. help();
  137. return -1;
  138. }
  139. FileStorage fs( calib_file, FileStorage::READ );
  140. if( !fs.isOpened() )
  141. {
  142. cout << "Failed to open Calibration Data File." << endl;
  143. help();
  144. return -1;
  145. }
  146. // Loading calibration parameters
  147. Mat cam1intrinsics, cam1distCoeffs, cam2intrinsics, cam2distCoeffs, R, T;
  148. fs["cam1_intrinsics"] >> cam1intrinsics;
  149. fs["cam2_intrinsics"] >> cam2intrinsics;
  150. fs["cam1_distorsion"] >> cam1distCoeffs;
  151. fs["cam2_distorsion"] >> cam2distCoeffs;
  152. fs["R"] >> R;
  153. fs["T"] >> T;
  154. cout << "cam1intrinsics" << endl << cam1intrinsics << endl;
  155. cout << "cam1distCoeffs" << endl << cam1distCoeffs << endl;
  156. cout << "cam2intrinsics" << endl << cam2intrinsics << endl;
  157. cout << "cam2distCoeffs" << endl << cam2distCoeffs << endl;
  158. cout << "T" << endl << T << endl << "R" << endl << R << endl;
  159. if( (!R.data) || (!T.data) || (!cam1intrinsics.data) || (!cam2intrinsics.data) || (!cam1distCoeffs.data) || (!cam2distCoeffs.data) )
  160. {
  161. cout << "Failed to load cameras calibration parameters" << endl;
  162. help();
  163. return -1;
  164. }
  165. size_t numberOfPatternImages = graycode->getNumberOfPatternImages();
  166. vector<vector<Mat> > captured_pattern;
  167. captured_pattern.resize( 2 );
  168. captured_pattern[0].resize( numberOfPatternImages );
  169. captured_pattern[1].resize( numberOfPatternImages );
  170. Mat color = imread( imagelist[numberOfPatternImages], IMREAD_COLOR );
  171. Size imagesSize = color.size();
  172. // Stereo rectify
  173. cout << "Rectifying images..." << endl;
  174. Mat R1, R2, P1, P2, Q;
  175. Rect validRoi[2];
  176. stereoRectify( cam1intrinsics, cam1distCoeffs, cam2intrinsics, cam2distCoeffs, imagesSize, R, T, R1, R2, P1, P2, Q, 0,
  177. -1, imagesSize, &validRoi[0], &validRoi[1] );
  178. Mat map1x, map1y, map2x, map2y;
  179. initUndistortRectifyMap( cam1intrinsics, cam1distCoeffs, R1, P1, imagesSize, CV_32FC1, map1x, map1y );
  180. initUndistortRectifyMap( cam2intrinsics, cam2distCoeffs, R2, P2, imagesSize, CV_32FC1, map2x, map2y );
  181. // Loading pattern images
  182. for( size_t i = 0; i < numberOfPatternImages; i++ )
  183. {
  184. captured_pattern[0][i] = imread( imagelist[i], IMREAD_GRAYSCALE );
  185. captured_pattern[1][i] = imread( imagelist[i + numberOfPatternImages + 2], IMREAD_GRAYSCALE );
  186. if( (!captured_pattern[0][i].data) || (!captured_pattern[1][i].data) )
  187. {
  188. cout << "Empty images" << endl;
  189. help();
  190. return -1;
  191. }
  192. remap( captured_pattern[1][i], captured_pattern[1][i], map1x, map1y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  193. remap( captured_pattern[0][i], captured_pattern[0][i], map2x, map2y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  194. }
  195. cout << "done" << endl;
  196. vector<Mat> blackImages;
  197. vector<Mat> whiteImages;
  198. blackImages.resize( 2 );
  199. whiteImages.resize( 2 );
  200. // Loading images (all white + all black) needed for shadows computation
  201. cvtColor( color, whiteImages[0], COLOR_RGB2GRAY );
  202. whiteImages[1] = imread( imagelist[2 * numberOfPatternImages + 2], IMREAD_GRAYSCALE );
  203. blackImages[0] = imread( imagelist[numberOfPatternImages + 1], IMREAD_GRAYSCALE );
  204. blackImages[1] = imread( imagelist[2 * numberOfPatternImages + 2 + 1], IMREAD_GRAYSCALE );
  205. remap( color, color, map2x, map2y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  206. remap( whiteImages[0], whiteImages[0], map2x, map2y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  207. remap( whiteImages[1], whiteImages[1], map1x, map1y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  208. remap( blackImages[0], blackImages[0], map2x, map2y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  209. remap( blackImages[1], blackImages[1], map1x, map1y, INTER_NEAREST, BORDER_CONSTANT, Scalar() );
  210. cout << endl << "Decoding pattern ..." << endl;
  211. Mat disparityMap;
  212. bool decoded = graycode->decode( captured_pattern, disparityMap, blackImages, whiteImages,
  213. structured_light::DECODE_3D_UNDERWORLD );
  214. if( decoded )
  215. {
  216. cout << endl << "pattern decoded" << endl;
  217. // To better visualize the result, apply a colormap to the computed disparity
  218. double min;
  219. double max;
  220. minMaxIdx(disparityMap, &min, &max);
  221. Mat cm_disp, scaledDisparityMap;
  222. cout << "disp min " << min << endl << "disp max " << max << endl;
  223. convertScaleAbs( disparityMap, scaledDisparityMap, 255 / ( max - min ) );
  224. applyColorMap( scaledDisparityMap, cm_disp, COLORMAP_JET );
  225. // Show the result
  226. resize( cm_disp, cm_disp, Size( 640, 480 ), 0, 0, INTER_LINEAR_EXACT );
  227. imshow( "cm disparity m", cm_disp );
  228. // Compute the point cloud
  229. Mat pointcloud;
  230. disparityMap.convertTo( disparityMap, CV_32FC1 );
  231. reprojectImageTo3D( disparityMap, pointcloud, Q, true, -1 );
  232. // Compute a mask to remove background
  233. Mat dst, thresholded_disp;
  234. threshold( scaledDisparityMap, thresholded_disp, 0, 255, THRESH_OTSU + THRESH_BINARY );
  235. resize( thresholded_disp, dst, Size( 640, 480 ), 0, 0, INTER_LINEAR_EXACT );
  236. imshow( "threshold disp otsu", dst );
  237. #ifdef HAVE_OPENCV_VIZ
  238. // Apply the mask to the point cloud
  239. Mat pointcloud_tresh, color_tresh;
  240. pointcloud.copyTo( pointcloud_tresh, thresholded_disp );
  241. color.copyTo( color_tresh, thresholded_disp );
  242. // Show the point cloud on viz
  243. viz::Viz3d myWindow( "Point cloud with color" );
  244. myWindow.setBackgroundMeshLab();
  245. myWindow.showWidget( "coosys", viz::WCoordinateSystem() );
  246. myWindow.showWidget( "pointcloud", viz::WCloud( pointcloud_tresh, color_tresh ) );
  247. myWindow.showWidget( "text2d", viz::WText( "Point cloud", Point(20, 20), 20, viz::Color::green() ) );
  248. myWindow.spin();
  249. #endif // HAVE_OPENCV_VIZ
  250. }
  251. waitKey();
  252. return 0;
  253. }