Depth Map from Stereo Images in Python

FeaImg DepthMap

In this tutorial, we’ll look at how to make a depth map from stereo pictures in Python using the OpenCV package. But first, let’s get a grasp on the notion of stereo pictures and image depth.

When we walk or run, we observe that items close to us appear to move quicker than those further away. This underlying effect is known as ‘parallax.’

This phenomenon may be used to derive geometrical information from any sight. We may estimate a variety of things from many photographs of the same arena from diverse points of view, one of which is the interspace of the components.

This distance is referred to as the image’s depth, and the pictures are referred to as stereo images. We can now determine the distance of these areas from the camera by investigating the span of points between these renderings.

Importing the libraries/modules

Let’s begin by importing the required libraries for our use cases. We’ll work with the numpy library, OpenCV, and matplotlib for the plotting.

import numpy as np
import cv2
from matplotlib import pyplot as plt

Loading the stereo images

Now let us load the stereo images.

imgL = cv2.imread('input_images/Stereo_Image_1.jpg',0)
imgR = cv2.imread('input_images/Stereo_Image_2.jpg',0)
Stereo Image 1
Stereo Image 1
Stereo Image 2
Stereo Image 2

Creating the depth map

The StereoBM_create() method will be used to generate the depth map. We can adjust the settings as needed. numDisparities accepts numbers up to 255 which is divisible by 16, but blockSize accepts values up to 25.

stereo = cv2.StereoBM_create(numDisparities=96, blockSize=15)
disparity = stereo.compute(imgL,imgR)
plt.figure(figsize = (20,10))
Depthmap Image Output
Depthmap Image Output

We can calculate the depth using the depth map. This includes camera arrangements and their interactions with picture discrepancies. This falls outside the scope of this tutorial, therefore we can’t go any farther.

This finishes the tutorial on how to construct a depth map from stereo pictures in Python using OpenCV. Much of the work remains on your shoulders since you must choose the appropriate map parameters analytically.


Congratulations! You just learned how to make a depth map from stereo pictures in Python using the OpenCV package. Hope you enjoyed it! 😇

Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:

  1. Visualizing Colors In Images Using Histograms – Python OpenCV
  2. Draw Shapes Using OpenCV – A Complete How-To Guide
  3. Live Sketch Using Webcam with Python OpenCV [Easy Guide]
  4. Credit Card Reader in Python using OpenCV

Thank you for taking your time out! Hope you learned something new!! 😄