How to Auto-Deskew Scanned Documents with OpenCV and Python: Step-by-Step Code Example

A page that fed through a scanner at a slight angle looks acceptable until OCR starts dropping words: every text line sits a degree or two off horizontal. Deskewing measures that tilt from the text lines themselves and rotates the whole page back, without changing its content.

There are two different problems that get called “deskewing”. A flat scan whose text lines are tilted needs only a rotation — that is what the OpenCV pipeline below does: grayscale, blur, Otsu threshold, horizontal dilation, contour angles, median, then cv2.warpAffine. A page photographed at an angle has perspective distortion as well; rotating a trapezoid can never make it a rectangle. That case needs four-corner detection and normalization, which is what Dynamsoft Capture Vision’s DDN module provides. Both produce a readable page, but only the first is a rotation.

What you’ll build: A Python script that measures text-line skew with OpenCV and rotates the image back, plus a browser demo that runs the same pipeline on a photographed page and on a flat scan.

Demo video:

Deskew vs Perspective Correction

  OpenCV text-line deskew (this tutorial) Dynamsoft Capture Vision DDN
Input Flat scan whose text lines are tilted Page photographed at an angle, with perspective distortion
What it measures Median minAreaRect angle of dilated text-line contours Four document corners via DetectDocumentBoundaries_Default
Transform One affine rotation (cv2.warpAffine) Perspective normalization (NormalizeDocument_Default)
Also handles One already-cropped page Multi-page capture, auto-capture stability, quad editing, PDF export
Dependency Free, Python + OpenCV dynamsoft-capture-vision-bundle@3.6.5000 via CDN plus a license key

The steps below implement the left column on a static image. If your input is a camera photo rather than a flat scan, start with the multi-page document scanner tutorial and the online demo.

The Minimal Path

# After Step 1 normalizes the page and dilates its text lines:
angles = [cv2.minAreaRect(c)[-1] for c in contours]
angle = sorted(angles)[len(angles) // 2]      # median text-line tilt
M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
deskewed = cv2.warpAffine(img, M, (w, h), borderValue=(255, 255, 255))

Everything in Steps 1–3 exists to make that median angle reliable.

Key Takeaways

  • OpenCV can auto-detect document skew angles by analyzing dilated text-line contours with minAreaRect and taking the median rotation angle.
  • Affine transformation via cv2.warpAffine rotates the scanned image to correct skew without cropping content.
  • Pre-processing steps — grayscale conversion, Gaussian blur, Otsu thresholding, and morphological dilation — are essential to isolate text lines for accurate angle detection.
  • For browser-based workflows, Dynamic Web TWAIN provides a built-in GetSkewAngle + Rotate API that handles deskewing without custom image processing code.
  • A photographed page needs more than rotation: Dynamsoft Capture Vision detects its four corners and normalizes the perspective before any deskew step.

Common Developer Questions

How do I auto-deskew a scanned document image with OpenCV in Python?

Convert the image to grayscale, threshold and dilate the text lines, measure contour angles with cv2.minAreaRect, and use the median angle as the skew estimate. Then rotate the page back with cv2.warpAffine to produce the deskewed result.

Why is my OpenCV deskew returning the wrong angle, and how do I fix it?

Wrong angles usually come from noisy contours, border artifacts, or keeping near-zero and 90-degree rectangles in the sample set. Cleaning the image first, removing borders, and filtering unusable contour angles before taking the median makes the deskew result much more stable.

What is the easiest way to deskew scanned documents in a web browser with JavaScript?

Use Dynamic Web TWAIN’s built-in GetSkewAngle and Rotate APIs if you want browser-side deskew without rebuilding the image-processing pipeline yourself. That approach skips custom OpenCV code and fits directly into scanning workflows on the web.

Why is deskew not enough for a document photographed with a phone?

Rotation only changes orientation. A phone photo also compresses the far edge of the page, so the four corners form a trapezoid rather than a rotated rectangle. Detect those corners and apply a perspective transform instead: the Capture Vision multi-page scanner tutorial shows DetectDocumentBoundaries_Default and NormalizeDocument_Default running frame by frame through CaptureVisionRouter.

Prerequisites

  • Python 3.6 or later
  • OpenCV installed (pip install opencv-python)
  • To try the browser-based approach with Dynamic Web TWAIN, get a 30-day free trial license.

The Python Pipeline

We are going to write a Python script to deskew the following sample image.

document

Step 1: Normalize the Scanned Image for Processing

  1. Scanned images are sharp. We can convert the image to grayscale and blur the image first.

    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (9, 9), 0)
    

    blur

  2. Resize the image with a fixed height.

    resized_height = 480
    percent = resized_height / len(img)
    resized_width = int(percent * len(img[0]))
    gray = cv2.resize(gray,(resized_width,resized_height))
    

    resized

  3. Draw a rectangle around the border to remove border lines.

    start_point = (0, 0) 
    end_point = (gray.shape[0], gray.shape[1]) 
    color = (255, 255, 255) 
    thickness = 10
    gray = cv2.rectangle(gray, start_point, end_point, color, thickness) 
    

    cropped

  4. Invert the image, since we have to process the text.

    gray = cv2.bitwise_not(gray)
    

    inverted

  5. Run thresholding to get a binary image.

    thresh = cv2.threshold(gray, 0, 255,
            cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    

    thresh

  6. Dilate the text to make the text lines more obvious.

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5))
    dilate = cv2.dilate(thresh, kernel)
    

    dilate

Step 2: Detect the Skew Angle from Text Lines

  1. Find all the contours based on the dilated image.

    contours, hierarchy = cv2.findContours(dilate, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    
  2. Use minAreaRect to get the rotation angles of contours.

    angles = []
    for contour in contours:
        minAreaRect = cv2.minAreaRect(contour)
        angle = minAreaRect[-1]
        if angle != 90.0 and angle != -0.0: #filter out 0 and 90
            angles.append(angle)
    
  3. Use the median as the skewed angle.

    angles.sort()
    mid_angle = angles[int(len(angles)/2)]
    

Step 3: Rotate the Image to Correct the Skew

After getting the skewed angle, we can perform affine transformation to get the deskewed image.

if angle > 45: #anti-clockwise
        angle = -(90 - angle)
height = original.shape[0]
width = original.shape[1]
m = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)
deskewed = cv2.warpAffine(original, m, (width, height), borderValue=(255,255,255))

deskewed

Measured Result on Two Inputs

The browser demo runs the same pipeline on OpenCV.js 4.13.0. Its default sample is a page photographed on a desk (samples/sample-desk.jpg, 1400 × 1860 px) so the sheet edge stays visible, and the second sample is a flat scan (samples/1.jpg, 1700 × 2338 px).

Input Text-line contours Median tilt Processing
Photo on a desk 30 −2.94° ≈180 ms
Flat scan 29 1.50° ≈160 ms

The blue boxes mark the detected text-line regions, the orange line is the measured tilt, and the right panel is the corrected page. warpAffine rotates the entire frame, so on a photo the desk rotates with the page: only the paper ends up level.

A photographed page with detected text-line regions beside its deskewed output

Two details start to matter once the input is a photograph instead of a scan. The paper outline is itself a long thin contour, so contours whose short side exceeds roughly 5% of the image’s short side have to be discarded before taking the median — otherwise the sheet boundary competes with the text lines. And the empty wedges left by the rotation should be filled with the page’s own corner tone rather than white, or a photo picks up four bright triangles that were never in the scene.

Verify the rotation direction on a known-skewed sample before batch processing, because minAreaRect reports angles in a version-dependent range.

Deskew in the Browser, and When to Move to a Production Scanner

Dynamic Web TWAIN exposes GetSkewAngle and Rotate for pages that are already inside a scanning workflow:

function Deskew(index) {
  return new Promise((resolve, reject) => {
    DWObject.GetSkewAngle(
      index,
      function(angle) {
        console.log("skew angle: " + angle);
        DWObject.Rotate(index, angle, true,
          function() { resolve(); },
          function(errorCode, errorString) { reject(errorString); }
        );
      },
      function(errorCode, errorString) { reject(errorString); }
    );
  })
}

The sample repository keeps that DWT app as dwt-index.html and adds an OpenCV.js baseline demo (index.html) that runs the contour algorithm client-side, with the detected text-line regions drawn over the input and a correction-angle slider. Both handle the flat-scan case.

For camera capture the limiting factor is no longer the rotation — it is finding the page at all. Dynamsoft Capture Vision returns a detected quad frame by frame through CaptureVisionRouter; the multi-page scanner tutorial implements DetectDocumentBoundaries_Default and NormalizeDocument_Default with an IoU plus area-delta stabilizer, and the online demo lets you test it with your own camera. Use that path when the input is a photo, when pages are captured in bulk, or when the page has perspective distortion. Get a 30-day free trial license to run it on your own host.

Common Issues and Edge Cases

  • Wrong skew angle on documents with few text lines: If the document has large images, tables, or very few text lines, the contour-based median angle may be unreliable. Filter contours by minimum area (e.g., cv2.contourArea(contour) > 100) to exclude noise before calculating the angle.
  • The page outline wins the vote on photos: A photographed sheet contributes one huge contour around the paper. It has more than enough area and its angle is the sheet’s own skew, so it lands in the middle of the median. Cap the contour’s short side — min(w, h) <= max(60, min(rows, cols) * 0.05) in the browser demo — so only text-shaped regions vote.
  • Black borders appear after rotation: cv2.warpAffine fills empty pixels with borderValue. For white-background documents set borderValue=(255,255,255); for a photo with a visible background, average the four corner pixels and use that colour so the wedges blend in. For skew angles beyond a few degrees, consider cropping the result.
  • Angle off by 90°: OpenCV’s minAreaRect returns angles in the range [−90°, 0°). A nearly-vertical rectangle may report −89° instead of −1°. The if angle > 45 guard in Step 3 handles this, but verify the direction by testing on a known-skewed sample first.
  • The page is still trapezoidal after deskewing: Rotation cannot fix perspective distortion. Detect the four corners and normalize instead — see the deskew vs perspective correction table and the Capture Vision tutorial.

Source Code

The Python script, ImageMagick command, DWT app and the OpenCV.js browser demo all live in the sample repository. Serve the folder with any static HTTP server and open index.html to try the bundled scans.

For the production path, see How to Build a JavaScript Multi-Page Document Scanner Web App with Auto-Capture and PDF Export and its online demo.