SBM_Sample.cpp 1.85 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/**
 * @file SBM_Sample
 * @brief Get a disparity map of two images
 * @author A. Huaman
 */

#include <stdio.h>
#include <iostream>
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/core/core.hpp"
11
#include "opencv2/imgcodecs.hpp"
12 13 14 15
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

16
const char *windowDisparity = "Disparity";
17 18 19 20 21 22 23 24 25 26 27 28 29

void readme();

/**
 * @function main
 * @brief Main function
 */
int main( int argc, char** argv )
{
  if( argc != 3 )
  { readme(); return -1; }

  //-- 1. Read the images
30 31
  Mat imgLeft = imread( argv[1], IMREAD_GRAYSCALE );
  Mat imgRight = imread( argv[2], IMREAD_GRAYSCALE );
32 33 34
  //-- And create the image in which we will save our disparities
  Mat imgDisparity16S = Mat( imgLeft.rows, imgLeft.cols, CV_16S );
  Mat imgDisparity8U = Mat( imgLeft.rows, imgLeft.cols, CV_8UC1 );
35

36
  if( imgLeft.empty() || imgRight.empty() )
37 38 39 40 41 42
  { std::cout<< " --(!) Error reading images " << std::endl; return -1; }

  //-- 2. Call the constructor for StereoBM
  int ndisparities = 16*5;   /**< Range of disparity */
  int SADWindowSize = 21; /**< Size of the block window. Must be odd */

43
  Ptr<StereoBM> sbm = StereoBM::create( ndisparities, SADWindowSize );
44 45

  //-- 3. Calculate the disparity image
46
  sbm->compute( imgLeft, imgRight, imgDisparity16S );
47 48 49 50 51 52 53 54 55 56 57

  //-- Check its extreme values
  double minVal; double maxVal;

  minMaxLoc( imgDisparity16S, &minVal, &maxVal );

  printf("Min disp: %f Max value: %f \n", minVal, maxVal);

  //-- 4. Display it as a CV_8UC1 image
  imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal));

58
  namedWindow( windowDisparity, WINDOW_NORMAL );
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  imshow( windowDisparity, imgDisparity8U );

  //-- 5. Save the image
  imwrite("SBM_sample.png", imgDisparity16S);

  waitKey(0);

  return 0;
}

/**
 * @function readme
 */
void readme()
{ std::cout << " Usage: ./SBMSample <imgLeft> <imgRight>" << std::endl; }