Document Scanner
π Overview
Photograph a paper document with a camera and it automatically finds the page edges, corrects the perspective, and sharpens the text, producing the kind of high-quality image a phone scanner app gives you.
The core technique is OpenCV contour detection plus a four-point perspective warp (warpPerspective) - a genuinely valuable classic pipeline in practical image processing.
π§° What you need
- Computer + camera (or a phone photo to import)
- Python 3.7+ environment
- pip install: opencv-python, numpy
- A document that contrasts clearly with the background
π§ Step by step
Load the image
Capture from the camera or read a local image file
Resize to a standard size first to speed up processing
Pre-process
Grayscale, then Gaussian blur, then Canny edge detection
The quality of this stage decides whether contour detection succeeds
Find the document contour
Use findContours to find the largest outer contour
Approximate it into a quadrilateral with approxPolyDP
Correct the perspective
Take the four corners and sort them as top-left/top-right/bottom-right/bottom-left
Straighten it with getPerspectiveTransform and warpPerspective
Enhance the output
Grayscale it or use adaptive thresholding to boost text contrast
Save it as an image - the scan is done
Wrap it into an app
Add key controls: space to scan, S to save
It can batch-process a folder of photos
π‘ Tips
- The stronger the contrast between page and background the better; a dark document on a light desktop works best
- Sort the corners with tricks such as 'smallest x+y is top-left, largest x-y is top-right' to avoid mix-ups
- Adaptive thresholding handles uneven lighting much better than a global threshold