A script for performing perspective transforms on images of documents to give a head-on view of them.
This script is designed to take an image of a document and perform a perspective transform to produce an output image as the document would appear from a head-on perspective.
The script differs slightly from the standard perspective transform tutorials in that it can warp shapes that are non-convex contours with more than 4 points (for example a document that has a sharp fold in it). This only works if a contour is detected around the document.
Should work with either Python 2.X or 3.X
Requires that you have the following packages installed:
OpenCV for the image processing.
NumPy and SciPy for the math and data types.
pip install opencv-python numpy scipy
- Launch the script
- If you use the command line you can provide two arguments (input_file and output_file)
- ex. python document_warp.py input_file.jpg
- ex. python document_warp.py input_file.jpg output_file.jpg
- Use the mouse to left-click on 4 points that are close to the corners of the document in your image.
- It's best if you click on points that are outside the corners of the document
- Red lines will be drawn, it's OK if they cross over parts of the document.
- Right-click to clear all the points you've selected.
- Hit the 'a' key to try to perform automatic selection of a bounding contour.
- The automatic selection does two things: gets 4 corner points that are on the bounding contour (for a regular perspective transform) and finds a contour around the document (for a grid perspective transform).
- Automatic selection will fail if the script cannot detect a contour around the document. High contrast images of the document against a background will help.
- Hit 'w' for a 'normal' perspective transform. This works well on documents that are smooth and flat. It will work regardless of whether automatic selection was able to find corners or a contour around the document.
- Hit 'g' for a 'grid' perspective transform.
- This only works if automatic selection was able to find a contour.
- In the script you can change the number of points in the grid (more points takes noticibly longer).
- The script doesn't try to adjust color/darkness so the output image will probably still look slightly bent because of the lighting of the original image.
- Hit 's' to save the output image (defaults to 'warp_output.jpg')
- Only works while the output image is visible.