How to Correct Skewed Text in Images Using OpenCV: A Step‑by‑Step Guide

This tutorial explains how to detect, calculate, and correct the rotation angle of text in an image using OpenCV, covering image binarization, minimum‑area bounding box extraction, angle adjustment, and affine transformation with clear Python code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Correct Skewed Text in Images Using OpenCV: A Step‑by‑Step Guide

Assume we have an image where the text is rotated by an unknown angle. To correct the orientation we follow four steps.

Step 1: Load image and binarize

img = cv.imread('img/imageTextR.png')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)

We invert the binary image so that the text becomes white on a black background.

Step 2: Compute the minimum‑area bounding box of the text region

coords = np.column_stack(np.where(thresh > 0))
angle = cv.minAreaRect(coords)[-1]

The cv.minAreaRect function returns a rectangle whose rotation matches the text rotation.

Step 3: Adjust the angle

if angle < -45:
    angle = -(90 + angle)
else:
    angle = -angle

If the angle is less than –45°, we add 90°; otherwise we simply negate it.

Step 4: Apply affine rotation

h, w = img.shape[:2]
center = (w // 2, h // 2)
M = cv.getRotationMatrix2D(center, angle, 1.0)
rotated = cv.warpAffine(img, M, (w, h), flags=cv.INTER_CUBIC, borderMode=cv.BORDER_REPLICATE)
cv.putText(rotated, f'Angle: {angle:.2f} degrees', (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)

The corrected image is displayed alongside the original.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Computer VisionPythonImage ProcessingOpenCVtext rotation
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.