21 May Perspective Transform Warping with OpenCV
Perspective transform (also called perspective warping) is a technique in OpenCV that allows you to change the perspective of an image to create a different viewpoint. It corrects perspective distortion (e.g., turning a tilted document into a flat view).
Uses of Perspective Transform
It’s commonly used for:
- Correcting perspective distortion (like making a tilted document appear flat)
- Creating bird’s-eye views (top-down perspective)
- Augmented reality applications
- Image stitching in panoramas
How Perspective Transform Works in OpenCV
The process involves:
- Identifying source points: The four corners of the region you want to transform
- Defining destination points: Where those corners should be mapped to in the output
- Calculating the transformation matrix: Using cv2.getPerspectiveTransform()
- Applying the transformation: Using cv2.warpPerspective()
Let us see an example to implement Perspective Transform in OpenCV:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import cv2 import numpy as np # Load image image = cv2.imread(r'C:\Users\hp\Downloads\Astronaut.png') h, w = image.shape[:2] # Define 4 source points (e.g., corners of a tilted object) src_points = np.float32([[50, 50], [200, 50], [50, 200], [200, 200]]) # Define 4 target points (desired straight rectangle) dst_points = np.float32([[0, 0], [w, 0], [0, h], [w, h]]) # Compute perspective transform matrix matrix = cv2.getPerspectiveTransform(src_points, dst_points) # Apply perspective warp warped = cv2.warpPerspective(image, matrix, (w, h)) # Display results cv2.imshow("Original", image) cv2.imshow("Warped Perspective", warped) cv2.waitKey(0) cv2.destroyAllWindows() |
Output
Practical Applications of Perspective Transform
- Document scanning: Convert a photo of a document taken at an angle to a flat, rectangular image
- License plate recognition: Normalize the view of tilted license plates
- Augmented reality: Map virtual objects to real-world surfaces
- Satellite imagery simulation: Create ground-level views from aerial photos
The key advantage of perspective transform over affine transform is that it can handle changes in perspective (converging parallel lines), while affine transforms only handle rotation, scaling, and translation while keeping parallel lines parallel.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- Apply Sepia Tone filter with OpenCV
- Generative AI Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments