import cv2 as cv
import numpy as np
from scipy import ndimage
def deskew_robust(img, angle_threshold=0.5):
"""
Robust image deskewing using multiple methods
"""
# Convert to grayscale
if len(img.shape) == 3:
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
else:
gray = img.copy()
# Try multiple methods and choose the most consistent result
angles = []
# Method 1: Hough Line Transform
angle1 = get_angle_hough_lines(gray)
if angle1 is not None:
angles.append(angle1)
# Method 2: Improved minAreaRect with preprocessing
angle2 = get_angle_min_area_rect(gray)
if angle2 is not None:
angles.append(angle2)
# Method 3: Projection profile method
angle3 = get_angle_projection_profile(gray)
if angle3 is not None:
angles.append(angle3)
if not angles:
return img # No reliable angle found
# Choose the median angle or most common angle
final_angle = np.median(angles)
# Only rotate if angle is significant
if abs(final_angle) < angle_threshold:
return img
return rotate_image(img, final_angle)
def get_angle_hough_lines(gray):
"""Get skew angle using Hough line detection"""
# Preprocessing
blurred = cv.GaussianBlur(gray, (3, 3), 0)
edges = cv.Canny(blurred, 50, 150, apertureSize=3)
# Detect lines
lines = cv.HoughLines(edges, 1, np.pi/180, threshold=100)
if lines is None:
return None
angles = []
for rho, theta in lines[:, 0]:
angle = np.degrees(theta) - 90
# Filter out vertical and horizontal lines
if -45 <= angle <= 45:
angles.append(angle)
if not angles:
return None
# Return median angle
return np.median(angles)
def get_angle_min_area_rect(gray):
"""Improved minAreaRect method with better preprocessing"""
# Multiple threshold methods
methods = [
cv.THRESH_BINARY_INV + cv.THRESH_OTSU,
cv.THRESH_BINARY + cv.THRESH_OTSU,
]
angles = []
for method in methods:
# Apply morphological operations to clean up
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
processed = cv.morphologyEx(gray, cv.MORPH_CLOSE, kernel)
_, thresh = cv.threshold(processed, 0, 255, method)
# Find contours instead of all white pixels
contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
if contours:
# Use the largest contour
largest_contour = max(contours, key=cv.contourArea)
if cv.contourArea(largest_contour) > 1000: # Filter small contours
rect = cv.minAreaRect(largest_contour)
angle = rect[-1]
# Normalize angle
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
angles.append(angle)
return np.median(angles) if angles else None
def get_angle_projection_profile(gray):
"""Get skew angle using projection profile method"""
# Threshold the image
_, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
# Test angles from -10 to 10 degrees
angles_to_test = np.arange(-10, 11, 0.5)
variances = []
for angle in angles_to_test:
# Rotate image
rotated = ndimage.rotate(thresh, angle, reshape=False, cval=0)
# Calculate horizontal projection
h_projection = np.sum(rotated, axis=1)
# Calculate variance of projection (higher variance = better alignment)
variances.append(np.var(h_projection))
# Find angle with maximum variance
best_angle_idx = np.argmax(variances)
return angles_to_test[best_angle_idx]
def rotate_image(img, angle):
"""Rotate image with proper size adjustment"""
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
# Calculate new image size to avoid cropping
angle_rad = np.radians(abs(angle))
new_w = int(h * np.sin(angle_rad) + w * np.cos(angle_rad))
new_h = int(h * np.cos(angle_rad) + w * np.sin(angle_rad))
# Get rotation matrix
M = cv.getRotationMatrix2D(center, angle, 1.0)
# Adjust translation to center the rotated image
M[0, 2] += (new_w - w) / 2
M[1, 2] += (new_h - h) / 2
# Rotate with new dimensions
rotated = cv.warpAffine(img, M, (new_w, new_h),
flags=cv.INTER_LINEAR,
borderMode=cv.BORDER_CONSTANT,
borderValue=(255, 255, 255))
return rotated
# Usage
def deskew_image(img):
return deskew_robust(img)