CoolFace
Apppublic

iluasdfiuasfd/DocScanner

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
rotation.py33 linesDownload Raw Back to modules
1import cv2
2import numpy as np
3
4def correct_angle_vertical(image, verbose=False):
5    """Correct the orientation of an image."""
6    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
7    ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
8    coords = np.column_stack(np.where(thresh > 0))
9    rect = cv2.minAreaRect(coords)
10    theta = rect[-1]
11
12    if theta < -45:
13        angle = -(theta + 90)
14    elif theta > 45:
15        angle = -(theta - 90)
16    else:
17        angle = -theta
18
19    h, w = image.shape[:2]
20    rotation_matrix = cv2.getRotationMatrix2D((w // 2, h // 2), angle, 1.0)
21    rotated = cv2.warpAffine(image, rotation_matrix, (w, h), flags=cv2.INTER_CUBIC, borderValue=(255, 255, 255))
22
23    gray_rotated = cv2.cvtColor(rotated, cv2.COLOR_RGB2GRAY)
24    _, mask = cv2.threshold(gray_rotated, 240, 255, cv2.THRESH_BINARY_INV)
25    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
26
27    all_points = np.vstack([pt for contour in contours for pt in contour])
28    hull = cv2.convexHull(all_points)
29    x, y, w, h = cv2.boundingRect(hull)
30
31    cropped = rotated[y + 3 : y + h - 3, x + 3 : x + w - 3]
32    return cropped
33