- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a depth map from stereo images in OpenCV Python?
A depth map can be created using stereo images. To construct a depth map from the stereo images, we find the disparities between the two images. For this we create an object of the StereoBM class using cv2.StereoBM_create() and compute the disparity using stereo.comput(). Where stereo is the created StereoBM object.
Steps
To create a depth map from the stereo images, you could follow the steps given below −
Import the required libraries OpenCV, Matplotlib and NumPy. Make sure you have already installed them.
Read two input images using cv2.imread()method as grayscale images. Specify the full path of the image.
Create a StereoBM object stereo = cv2.StereoBM_create() passing the desired numDisparities and blockSize.
Compute the disparity map between the input images using stereo.compute().To get a better result you can adjust the values of numDisparities and blockSize.
Visualize the disparity map (depth map).
Let's look at some examples to create a depth map from the stereo images.
Example
In this Python code, we create a depth map using stereo images.
# import required libraries import numpy as np import cv2 from matplotlib import pyplot as plt # read two input images as grayscale images imgL = cv2.imread('L.png',0) imgR = cv2.imread('R.png',0) # Initiate and StereoBM object stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15) # compute the disparity map disparity = stereo.compute(imgL,imgR) plt.imshow(disparity,'gray') plt.show() disparity.shape
We will use the following images as the Input Files in the above program −
Output
When you run the above Python program, it will produce the following output window −
Let's look at another example.
Example
In this Python code, we create a depth map using two stereo images.
# import required libraries import numpy as np import cv2 from matplotlib import pyplot as plt # read two input images imgL = cv2.imread('aloeL.jpg',0) imgR = cv2.imread('aloeR.jpg',0) # Initiate and StereoBM object stereo = cv2.StereoBM_create(numDisparities=128, blockSize=15) # compute the disparity map disparity = stereo.compute(imgL,imgR) disparity1 = stereo.compute(imgR,imgL) plt.imshow(disparity,'gray') plt.show()
We will use the following images as the Input Files in the above program −
Output
When you run the above Python program, it will produce the following output window −