File size: 3,535 Bytes
37d841f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import cv2
import numpy as np


def _order_points(pts):
    rect = np.zeros((4, 2), dtype='float32')
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmax(s)]
    d = np.diff(pts, axis=1)
    rect[1] = pts[np.argmin(d)]
    rect[3] = pts[np.argmax(d)]
    return rect


def _apply_perspective(img, pts):
    rect = _order_points(pts.astype('float32'))
    width_top    = np.linalg.norm(rect[1] - rect[0])
    width_bot    = np.linalg.norm(rect[2] - rect[3])
    height_left  = np.linalg.norm(rect[3] - rect[0])
    height_right = np.linalg.norm(rect[2] - rect[1])
    max_width  = int(max(width_top, width_bot))
    max_height = int(max(height_left, height_right))
    scale      = 800 / max_width
    target_w   = 800
    target_h   = max(600, min(int(max_height * scale), 1400))
    dst = np.array([[0, 0], [target_w, 0], [target_w, target_h], [0, target_h]], dtype='float32')
    M   = cv2.getPerspectiveTransform(rect, dst)
    return cv2.warpPerspective(img, M, (target_w, target_h))


def _method1_paper_edges(img):
    gray    = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (7, 7), 0)
    edges   = cv2.Canny(blurred, 30, 100)
    edges   = cv2.dilate(edges, None, iterations=2)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return None
    img_area = img.shape[0] * img.shape[1]
    for cnt in sorted(contours, key=cv2.contourArea, reverse=True)[:5]:
        if cv2.contourArea(cnt) < img_area * 0.2:
            continue
        epsilon = 0.02 * cv2.arcLength(cnt, True)
        approx  = cv2.approxPolyDP(cnt, epsilon, True)
        if len(approx) == 4:
            return _apply_perspective(img, approx.reshape(4, 2))
    return None


def _method2_grid_lines(img):
    gray    = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    binary  = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                    cv2.THRESH_BINARY_INV, 15, 10)
    h, w = binary.shape
    h_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (w // 8, 1))
    h_lines  = cv2.morphologyEx(binary, cv2.MORPH_OPEN, h_kernel, iterations=2)
    v_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, h // 8))
    v_lines  = cv2.morphologyEx(binary, cv2.MORPH_OPEN, v_kernel, iterations=2)
    grid     = cv2.dilate(cv2.add(h_lines, v_lines), None, iterations=3)
    contours, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return None
    largest = max(contours, key=cv2.contourArea)
    if cv2.contourArea(largest) < (h * w) * 0.15:
        return None
    for source in [largest, cv2.convexHull(largest)]:
        epsilon = 0.02 * cv2.arcLength(source, True)
        approx  = cv2.approxPolyDP(source, epsilon, True)
        if len(approx) == 4:
            return _apply_perspective(img, approx.reshape(4, 2))
    return None


def _method3_fallback(img):
    h, w  = img.shape[:2]
    scale = 800 / w
    return cv2.resize(img, (800, int(h * scale)))


def rectify_scoresheet(img: np.ndarray) -> tuple[np.ndarray, str]:
    """Rectifica la perspectiva de una planilla. Devuelve (imagen_rectificada, metodo_usado)."""
    result = _method1_paper_edges(img)
    if result is not None:
        return result, "metodo1_bordes_papel"
    result = _method2_grid_lines(img)
    if result is not None:
        return result, "metodo2_grilla"
    return _method3_fallback(img), "metodo3_fallback"