title: Calculate distance (disparity) OpenCV
body: <p><strong>-- Update 2 --</strong></p>
  
  <p>The following article is really useful (although it is using Python instead of C++) if you are using a single camera to calculate the distance: <a href="https://www.pyimagesearch.com/2015/01/19/find-distance-camera-objectmarker-using-python-opencv/" rel="nofollow noreferrer">Find distance from camera to object/marker using Python and OpenCV</a></p>
  
  <p><strong><em>Best link</em></strong> is <a href="https://github.com/mkokshoorn/Stereo-Webcam-Depth-Detection" rel="nofollow noreferrer">Stereo Webcam Depth Detection</a>. The implementation of this open source project is really clear.</p>
  
  <p>Below is the original question.</p>
  
  <hr>
  
  <p>For my project I am using two camera's (stereo vision) to track objects and to calculate the distance. I calibrated them with the sample code of OpenCV and generated a disparity map.</p>
  
  <p>I already implemented a method to track objects based on color (this generates a threshold image).</p>
  
  <p>My question: How can I calculate the distance to the tracked colored objects using the disparity map/ matrix?</p>
  
  <p>Below you can find a code snippet that gets the x,y and z coordinates of each pixel. The question: Is Point.z in cm, pixels, mm?</p>
  
  <p>Can I get the distance to the tracked object with this code?</p>
  
  <p>Thank you in advance!</p>
  
  <pre><code>cvReprojectImageTo3D(disparity, Image3D, _Q);
  
  vector&lt;CvPoint3D32f&gt; PointArray;
  CvPoint3D32f Point;
  
  for (int y = 0; y &lt; Image3D-&gt;rows; y++) {    
  
      float *data = (float *)(Image3D-&gt;data.ptr + y * Image3D-&gt;step);  
  
      for (int x = 0; x &lt; Image3D-&gt;cols * 3; x = x + 3) 
      {   
          Point.x = data[x];        
          Point.y =  data[x+1];     
          Point.z = data[x+2];
          PointArray.push_back(Point);
          //Depth &gt; 10
          if(Point.z &gt; 10)
          {
              printf("%f %f %f", Point.x, Point.y, Point.z);              
          }
      }
  }
  cvReleaseMat(&amp;Image3D);
  </code></pre>
  
  <p>--<strong>Update 1</strong>--</p>
  
  <p>For example I generated this thresholded image (of the left camera). I almost have the same of the right camera. </p>
  
  <p><img src="https://i.stack.imgur.com/6xJV1.png" alt="enter image description here"></p>
  
  <p>Besides the above threshold image, the application generates a disparity map. How can I get the Z-coordinates of the pixels of the hand in the disparity map? </p>
  
  <p>I actually want to get all the Z-coordinates of the pixels of the hand to calculate the average Z-value (distance) (using the disparity map).</p>