Skip to main content

Lesson 2 of 12

Document Scanner

Build a document scanner that detects the edges of a document in a photo and applies a perspective transformation to produce a flat, properly cropped scan.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Project Overview

Project: Document Scanner

What it does:
- Detects the four corners of a document in a photo
- Applies perspective transformation to correct camera angle
- Produces a clean flat scan from a hand-held phone photo
- Enhances contrast for better readability

Skills used:
- Module 3: Image processing (resize, grayscale)
- Module 5: Edge detection and contours
- Module 6: Perspective transform via homography

Diagram
Loading diagram…

Machine Learning follows a structured pipeline from data to deployment

Complete Implementation

Complete Implementation
import cv2
import numpy as np

class DocumentScanner:
    """
    Detects a document in a photo and transforms it
    into a flat, de-warped scan.
    """

    def order_corners(self, pts):
        """Order four corner points: top-left, top-right, bottom-right, bottom-left."""
        rect = np.zeros((4, 2), dtype=np.float32)
        s = pts.sum(axis=1)
        rect[0] = pts[np.argmin(s)]  # Top-left: smallest sum
        rect[2] = pts[np.argmax(s)]  # Bottom-right: largest sum
        diff = np.diff(pts, axis=1)
        rect[1] = pts[np.argmin(diff)]  # Top-right: smallest diff
        rect[3] = pts[np.argmax(diff)]  # Bottom-left: largest diff
        return rect

    def find_document_contour(self, image):
        """Find the contour of the document in the image."""
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        edges = cv2.Canny(blurred, 75, 200)

        # Dilate edges to close gaps
        kernel = np.ones((3, 3), np.uint8)
        edges = cv2.dilate(edges, kernel)

        contours, _ = cv2.findContours(
            edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )

        # Find the largest 4-sided contour (the document)
        contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]

        for contour in contours:
            peri = cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
            if len(approx) == 4:
                return approx.reshape(4, 2)

        return None

    def scan(self, image_path, output_path="scanned.jpg"):
        """Scan the document in the image."""
        image = cv2.imread(image_path)
        if image is None:
            print(f"Could not load: {image_path}")
            return None

        h, w = image.shape[:2]

        # Detect document corners
        corners = self.find_document_contour(image)

        if corners is None:
            print("Could not find document — using full image")
            corners = np.array([[0,0],[w,0],[w,h],[0,h]], dtype=np.float32)
        else:
            print(f"Document corners found: {corners}")

        # Order corners and compute output size
        rect = self.order_corners(corners)
        tl, tr, br, bl = rect

        width  = int(max(np.linalg.norm(br-bl), np.linalg.norm(tr-tl)))
        height = int(max(np.linalg.norm(tr-br), np.linalg.norm(tl-bl)))

        # Destination points (flat rectangle)
        dst = np.array([[0,0],[width-1,0],[width-1,height-1],[0,height-1]],
                       dtype=np.float32)

        # Perspective transform
        M = cv2.getPerspectiveTransform(rect, dst)
        warped = cv2.warpPerspective(image, M, (width, height))

        # Enhance for readability
        gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
        enhanced = cv2.adaptiveThreshold(
            gray, 255,
            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            cv2.THRESH_BINARY,
            blockSize=11, C=10
        )

        # Draw detected corners on original
        result_image = image.copy()
        for corner in corners:
            cv2.circle(result_image, tuple(corner.astype(int)), 8, (0,255,0), -1)

        cv2.imwrite(output_path, enhanced)
        cv2.imwrite("scan_corners.jpg", result_image)
        print(f"Scan saved: {output_path}")
        print(f"Output size: {width}x{height}")
        return enhanced

scanner = DocumentScanner()
scanner.scan("document_photo.jpg", "clean_scan.jpg")

Topics in This Module

0/12 done