title: Disparity Map implementation in Python not matching in-built OpenCV function
body: <p>I'm facing an issue, and would like some inputs from the community on how to improve the disparity map. I'm following <a href="https://sites.google.com/site/5kk73gpu2010/assignments/stereo-vision#TOC-Update-Disparity-Map" rel="nofollow noreferrer">this tutorial</a> for calculating the disparity map between 2 images. The code I have is as follows:</p>
  
  <pre><code>import cv2
  import numpy as np
  import sys
  from matplotlib import pyplot as plt
  
  num_disparities = 64  # number of disparities to check
  block = 9  # block size to match
  
  def preprocess_frame(path):
      image = cv2.imread(path, 0)
      image = cv2.equalizeHist(image)
      image = cv2.GaussianBlur(image, (5, 5), 0)
      return image
  
  def calculate_disparity_matrix(args):
      left_image = preprocess_frame(args[1])
      right_image = preprocess_frame(args[2])
      rows, cols = left_image.shape
  
      kernel = np.ones([block, block]) / block
  
      disparity_maps = np.zeros(
          [left_image.shape[0], left_image.shape[1], num_disparities])
      for d in range(0, num_disparities):
          # shift image
          translation_matrix = np.float32([[1, 0, d], [0, 1, 0]])
          shifted_image = cv2.warpAffine(
              right_image, translation_matrix,
              (right_image.shape[1], right_image.shape[0]))
          # calculate squared differences
          SAD = abs(np.float32(left_image) - np.float32(shifted_image))
          # convolve with kernel and find SAD at each point
          filtered_image = cv2.filter2D(SAD, -1, kernel)
          disparity_maps[:, :, d] = filtered_image
  
      disparity = np.argmin(disparity_maps, axis=2)
      disparity = np.uint8(disparity * 255 / num_disparities)
      disparity = cv2.equalizeHist(disparity)
      plt.imshow(disparity, cmap='gray', vmin=0, vmax=255)
      plt.show()
  
  
  def calculate_disparity_inbuilt(args):
      left_image = preprocess_frame(args[1])
      right_image = preprocess_frame(args[2])
      rows, cols = left_image.shape
      stereo = cv2.StereoBM_create(numDisparities=num_disparities,
                                   blockSize=block)
      disparity = stereo.compute(left_image, right_image)
      plt.imshow(disparity, cmap='gray', vmin=0, vmax=255)
      plt.show()
  </code></pre>
  
  <p>The problem is that the output that I get from the inbuilt function in OpenCV is hardly similar to the one I've implemented. I was expecting at least a slight similarity between the 2. Is this expected? or am I doing something wrong here?</p>
  
  <p><a href="https://i.stack.imgur.com/LxQdA.png" rel="nofollow noreferrer">Implemented Algorithm</a>
  <a href="https://i.stack.imgur.com/KZCHH.png" rel="nofollow noreferrer">OpenCV Algorithm</a></p>