You can turn an angled photograph of a single sheet of paper into a scan-like, top-down image with a classical OpenCV pipeline: resize a working copy, detect edges, find a document-shaped contour, order its four corners, apply a perspective transform, and enhance the flattened result.
This creates a rectified image. It does not automatically create searchable text, understand forms, dewarp a curved book page, or deliver the reliability of a production scanning SDK. OCR, PDF packaging, and document understanding are separate stages.
What this scanner does—and does not do
- Scanning: finds the page boundary and removes perspective distortion.
- Enhancement: produces color, grayscale, or adaptive black-and-white output.
- OCR: converts pixels into text with a tool such as Tesseract or a hosted API.
- Document understanding: extracts fields, tables, entities, or classifications.
- PDF generation: packages one or more images into a PDF.
The contour method works best when one approximately rectangular page dominates the frame, its corners are visible, and the page contrasts with the background. It is excellent for learning and controlled prototypes, but clutter, shadows, curled pages, multiple sheets, and cropped corners require stronger methods.
The overall flow is:
Input image → resized working copy → grayscale and blur → Canny edges → contours → four-corner candidate → ordered corners → perspective warp → color, grayscale, or binary enhancement → image/PDF/OCR
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
The classic contour-and-warp approach is documented in the PyImageSearch document-scanner tutorial; the implementation below adds validation and explicit failure handling.
Assumptions behind the simple algorithm
Before writing code, make the assumptions explicit:
- There is one main document in the photograph.
- The page is roughly rectangular and mostly planar.
- Most or all four corners are visible.
- The page boundary has usable contrast against its surroundings.
- The page is likely to be the largest relevant contour.
- The image is not dominated by other rectangular objects or dense background texture.
If these assumptions are routinely false, use a line-based detector, marker-assisted capture, segmentation model, or commercial scanner SDK instead of endlessly tuning Canny thresholds.
Set up a modern Python project
Use Python 3 and keep the original photographs separate from generated files.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1
python -m pip install --upgrade pip
python -m pip install opencv-python numpy
# Optional helpers
python -m pip install imutils scikit-image
The opencv-python package supplies OpenCV bindings and Tesseract is a separate local OCR option. Pin the versions you test in a requirements file for reproducible deployments.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Implement the scanner
Save the following as scanner.py. It resizes only a working image, maps detected points back to the original, rejects small or non-convex candidates, and offers color, grayscale, and adaptive-binary output.
from pathlib import Path
import argparse
import cv2
import numpy as np
def order_points(points: np.ndarray) -> np.ndarray:
"""Return four points in top-left, top-right, bottom-right, bottom-left order."""
points = np.asarray(points, dtype=np.float32)
if points.shape != (4, 2):
raise ValueError("Expected exactly four 2D points")
result = np.zeros((4, 2), dtype=np.float32)
sums = points.sum(axis=1)
differences = np.diff(points, axis=1).ravel()
result[0] = points[np.argmin(sums)] # top-left
result[2] = points[np.argmax(sums)] # bottom-right
result[1] = points[np.argmin(differences)] # top-right
result[3] = points[np.argmax(differences)] # bottom-left
return result
def four_point_warp(image: np.ndarray, points: np.ndarray) -> np.ndarray:
rect = order_points(points)
tl, tr, br, bl = rect
top = np.linalg.norm(tr - tl)
bottom = np.linalg.norm(br - bl)
left = np.linalg.norm(bl - tl)
right = np.linalg.norm(br - tr)
width = max(1, int(round(max(top, bottom))))
height = max(1, int(round(max(left, right))))
destination = np.array([
[0, 0], [width - 1, 0],
[width - 1, height - 1], [0, height - 1]
], dtype=np.float32)
matrix = cv2.getPerspectiveTransform(rect, destination)
return cv2.warpPerspective(image, matrix, (width, height))
def find_document_contour(edged: np.ndarray, min_area_ratio: float = 0.10):
contours, _ = cv2.findContours(
edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
)
image_area = edged.shape[0] * edged.shape[1]
candidates = []
for contour in contours:
area = cv2.contourArea(contour)
if area < image_area * min_area_ratio:
continue
perimeter = cv2.arcLength(contour, True)
if perimeter <= 0:
continue
polygon = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
if len(polygon) != 4 or not cv2.isContourConvex(polygon):
continue
candidates.append((area, polygon.reshape(4, 2)))
if not candidates:
return None
candidates.sort(key=lambda item: item[0], reverse=True)
return candidates[0][1]
def scan_image(path: str, resize_height: int = 800,
min_area_ratio: float = 0.10) -> np.ndarray:
original = cv2.imread(path)
if original is None:
raise FileNotFoundError(f"Could not read image: {path}")
original_height = original.shape[0]
if original_height > resize_height:
scale = original_height / float(resize_height)
working = cv2.resize(
original, None, fx=1 / scale, fy=1 / scale,
interpolation=cv2.INTER_AREA
)
else:
working = original.copy()
scale = 1.0
gray = cv2.cvtColor(working, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 50, 150)
contour = find_document_contour(edged, min_area_ratio)
if contour is None:
raise RuntimeError(
"No document-like four-corner contour found. Improve lighting, "
"use a contrasting background, or lower --min-area-ratio carefully."
)
return four_point_warp(original, contour * scale)
def enhance(image: np.ndarray, mode: str, block_size: int, offset: int):
if mode == "color":
return image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if mode == "gray":
return gray
if block_size & 1 == 0 or block_size <= 1:
raise ValueError("--block-size must be an odd integer greater than one")
return cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, block_size, offset
)
def main():
parser = argparse.ArgumentParser(description="Rectify a photographed document")
parser.add_argument("input")
parser.add_argument("-o", "--output", default="scan.png")
parser.add_argument("--mode", choices=("color", "gray", "bw"), default="gray")
parser.add_argument("--resize-height", type=int, default=800)
parser.add_argument("--min-area-ratio", type=float, default=0.10)
parser.add_argument("--block-size", type=int, default=11)
parser.add_argument("--threshold-offset", type=int, default=10)
args = parser.parse_args()
warped = scan_image(args.input, args.resize_height, args.min_area_ratio)
result = enhance(warped, args.mode, args.block_size, args.threshold_offset)
if not cv2.imwrite(args.output, result):
raise OSError(f"Could not write output: {args.output}")
print(f"Saved scanned document to {Path(args.output).resolve()}")
if __name__ == "__main__":
main()
Run it and choose an output mode
python scanner.py receipt.jpg --output receipt-scan.png --mode gray
python scanner.py form.jpg --output form-bw.png --mode bw --block-size 11 --threshold-offset 10
python scanner.py photo.jpg --output photo-color.png --mode color
Color
Use color for receipts with colored marks, identity documents, photographs, stamps, or forms where color carries meaning.
Grayscale
Grayscale is a sensible default for printed pages and OCR preparation because it preserves more detail than binary output while reducing file size.
Adaptive binary
Adaptive thresholding can produce a traditional black-and-white scanner appearance under uneven lighting. It can also erase faint strokes, pencil, colored ink, stamps, and photographs. Keep the grayscale result when it contains information the binary version loses.
Why each processing step matters
Resize the working copy
Phone photographs are large, so contour detection is faster on a reduced image. Keep the original for the final warp, and multiply the detected coordinates by the original-to-working scale. Do not enlarge an image that is already smaller than the target height.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Grayscale and Gaussian blur
Grayscale reduces three color channels to one intensity channel. A typical (5, 5) Gaussian kernel suppresses small texture and sensor noise before edge detection. It is a starting point, not a universal setting.
Canny edges
Canny creates a binary edge map. The example uses 50 and 150; tutorial values such as 75 and 200 are also common. Exposure, contrast, and background texture determine whether fixed thresholds work. Production systems may normalize contrast, choose thresholds adaptively, or use morphological closing.
Contours and polygon approximation
Contours are sorted by area and approximated with a tolerance of two percent of their perimeter. A four-vertex, convex polygon with sufficient area is a candidate—not proof that it is the page. A laptop screen, table edge, picture frame, tile, or second sheet may win the largest-contour heuristic.
Corner ordering
The transform requires a consistent top-left, top-right, bottom-right, bottom-left order. Coordinate sums identify the two diagonal corners; coordinate differences identify the other two. Keeping this logic in a helper avoids subtle rotations and crossed quadrilaterals.
Perspective transformation
cv2.getPerspectiveTransform computes a homography from the four source points to a rectangle, and cv2.warpPerspective samples the original image into that rectangle. Width and height are estimated from the longest opposite sides rather than hard-coded.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Improve candidate selection when the largest rectangle is wrong
For a more reliable detector, score every plausible quadrilateral instead of returning the first one. Useful evidence includes:
- Area as a fraction of the image.
- Convexity and absence of self-intersection.
- Reasonable interior angles and aspect ratio.
- Strong edge support along all four sides.
- Distance from image borders; a contour touching a border may be a crop.
- A filled interior rather than a thin unrelated frame.
For interactive software, draw the selected points and let the user tap or correct the page. For difficult backgrounds, consider Hough-line grouping, thresholded connected components, a document-segmentation model, or marker-assisted capture.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Diagnose common failures
No document found
- Improve illumination and use a contrasting surface.
- Try local contrast enhancement or adaptive thresholding before contour extraction.
- Use morphological closing to bridge broken edges.
- Lower
--min-area-ratiocautiously; too low admits noise. - Use a line-based or learned detector when corners are missing or edges are weak.
The wrong rectangle is selected
Rank candidates with geometry and edge-support scores, penalize border-touching shapes, enforce an expected aspect ratio where appropriate, or ask the user to select the page. Never describe the largest four-point contour as guaranteed to be the document.
The warp is twisted or rotated
Inspect a debug image with numbered corners. Check clockwise ordering, reject self-intersecting polygons, and verify that width uses the top and bottom pairs while height uses the left and right pairs.
Binary output is worse
Return to color or grayscale, correct uneven illumination first, and tune block size and offset for the document class. Binary output is an option, not a quality guarantee.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Receipts, books, and multiple pages
Long receipts may be rejected by a fixed area ratio; curled pages cannot be fully corrected by a planar homography; and the single-contour pipeline is not a multi-page detector. Process pages individually or adopt a segmentation/dewarping approach.
Add OCR only after rectification
A sensible architecture is capture → page detection → perspective correction → enhancement → OCR → searchable PDF or structured export. Applying OCR to the flattened page usually gives the recognizer a more stable geometry, but accuracy still depends on resolution, blur, language, typography, layout, and preprocessing.
- Tesseract: local and open source; useful when privacy and offline operation matter, but it requires language data and tuning.
- Google Document AI: hosted OCR and structured processors; see product documentation and pricing.
- Amazon Textract: hosted text, forms, tables, expense, and identity-document analysis; see Textract and pricing.
- Azure AI Document Intelligence: Read OCR for printed and handwritten text and document extraction; see the product page and Read documentation.
Cloud services add network dependency, usage charges, vendor lock-in, and a data-handling decision. IDs, medical records, financial statements, and legal documents may be better kept entirely local.
Test against the images you actually need to scan
Do not infer production quality from one successful photograph. Build a representative test set containing:
- White paper on a dark desk and on a white desk.
- Hard shadows, low light, glare, and colored paper.
- Strong perspective and partially cropped corners.
- Receipts, handwriting, stamps, and photographs.
- Books and curled pages.
- Multiple sheets and rectangular background distractors.
Record whether detection succeeds, whether all four corners are plausible, whether text remains readable, and whether color or binary enhancement preserves the required content. Add explicit user-facing states such as “no document found,” “document too small,” “only three corners visible,” and “image too blurry,” rather than silently saving a bad scan.
When OpenCV is enough
Use this local pipeline for education, offline utilities, privacy-sensitive workflows, controlled capture stations, and small prototypes that need a flattened image. Choose a scanner SDK or document-intelligence service when you need live framing guidance, difficult-background robustness, multi-page capture, handwriting, table and form extraction, identity-document processing, curved-page correction, or auditable production accuracy.
The Bottom Line
OpenCV can produce a useful scan-like image with a compact classical pipeline, provided the page is a visible, mostly planar rectangle. Treat contour selection and threshold values as heuristics, preserve a color or grayscale fallback, and add OCR or document intelligence only as a separate stage.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →

