File size: 8,167 Bytes
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import cv2
import numpy as np

from ocr_config import (
    ANGLE_PROBE_BUCKET_DEGREES,
    ANGLE_PROBE_DUPLICATE_TOLERANCE,
    ANGLE_PROBE_MAX_ABS,
    ANGLE_PROBE_MAX_PASSES,
    ANGLE_PROBE_MIN_ABS,
    MAX_ARBITRARY_ROTATION_LONG_SIDE,
    MAX_ARBITRARY_ROTATION_PIXELS,
    MAX_CROP_LONG_SIDE,
    MAX_CROP_PIXELS,
    MAX_CROP_UPSCALE,
    MAX_FULL_FRAME_FAST_PASSES,
    MAX_FULL_FRAME_LONG_SIDE,
    MAX_FULL_FRAME_PIXELS,
    MAX_FULL_FRAME_UPSCALE,
    MAX_IMAGE_LONG_SIDE,
    MAX_IMAGE_PIXELS,
    MAX_IMAGE_UPSCALE,
    MIN_CROP_OCR_HEIGHT,
    MIN_CROP_OCR_WIDTH,
    MIN_FULL_FRAME_OCR_HEIGHT,
    MIN_FULL_FRAME_OCR_WIDTH,
    MIN_IMAGE_OCR_HEIGHT,
    MIN_IMAGE_OCR_WIDTH,
)


def rotate_image(image, angle):
    normalized = angle % 360

    if normalized == 0:
        return image

    if angle == 90:
        return cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
    if angle == 180:
        return cv2.rotate(image, cv2.ROTATE_180)
    if angle == 270:
        return cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)

    height, width = image.shape[:2]
    center = (width / 2, height / 2)
    matrix = cv2.getRotationMatrix2D(center, -angle, 1)
    cosine = abs(matrix[0, 0])
    sine = abs(matrix[0, 1])
    rotated_width = int((height * sine) + (width * cosine))
    rotated_height = int((height * cosine) + (width * sine))

    matrix[0, 2] += (rotated_width / 2) - center[0]
    matrix[1, 2] += (rotated_height / 2) - center[1]

    rotated = cv2.warpAffine(
        image,
        matrix,
        (rotated_width, rotated_height),
        flags=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_CONSTANT,
        borderValue=(255, 255, 255),
    )

    pixel_count = max(rotated_width * rotated_height, 1)
    downscale = min(
        MAX_ARBITRARY_ROTATION_LONG_SIDE / max(rotated_width, rotated_height),
        (MAX_ARBITRARY_ROTATION_PIXELS / pixel_count) ** 0.5,
        1,
    )

    if downscale >= 1:
        return rotated

    return cv2.resize(
        rotated,
        (round(rotated_width * downscale), round(rotated_height * downscale)),
        interpolation=cv2.INTER_AREA,
    )


def normalized_small_angle(angle):
    while angle <= -180:
        angle += 360
    while angle > 180:
        angle -= 360
    return angle


def line_angle_degrees(x1, y1, x2, y2):
    angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))

    while angle <= -90:
        angle += 180
    while angle > 90:
        angle -= 180

    return angle


def collect_line_angles(image, max_sample_side=900):
    height, width = image.shape[:2]
    max_side = max(height, width)
    scale = min(1, max_sample_side / max(max_side, 1))
    sample = image

    if scale < 1:
        sample = cv2.resize(
            image,
            (round(width * scale), round(height * scale)),
            interpolation=cv2.INTER_AREA,
        )

    gray = cv2.cvtColor(sample, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (3, 3), 0)
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    sample_height, sample_width = sample.shape[:2]
    min_line_length = max(40, round(min(sample_width, sample_height) * 0.14))
    lines = cv2.HoughLinesP(
        edges,
        1,
        np.pi / 180,
        threshold=60,
        minLineLength=min_line_length,
        maxLineGap=16,
    )

    if lines is None:
        return []

    line_angles = []
    for line in lines:
        x1, y1, x2, y2 = line[0]
        length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
        if length < min_line_length:
            continue

        angle = line_angle_degrees(x1, y1, x2, y2)
        line_angles.append((angle, length))

    return line_angles


def detect_skew_probe_rotations(image):
    buckets = {}

    for angle, length in collect_line_angles(image):
        if not ANGLE_PROBE_MIN_ABS <= abs(angle) <= ANGLE_PROBE_MAX_ABS:
            continue

        bucket = round(angle / ANGLE_PROBE_BUCKET_DEGREES) * ANGLE_PROBE_BUCKET_DEGREES
        buckets[bucket] = buckets.get(bucket, 0) + length

    rotations = []
    for angle, _weight in sorted(buckets.items(), key=lambda item: item[1], reverse=True):
        rotation = normalized_small_angle(-angle)
        if ANGLE_PROBE_MIN_ABS <= abs(rotation) <= ANGLE_PROBE_MAX_ABS:
            rotations.append(rotation)
        if len(rotations) >= 2:
            break

    return rotations


def add_cardinal_rotation(rotations, rotation):
    rotation = rotation % 360
    if rotation not in rotations:
        rotations.append(rotation)


def detect_cardinal_rotation_order(_image):
    rotations = []

    add_cardinal_rotation(rotations, 0)
    add_cardinal_rotation(rotations, 90)
    add_cardinal_rotation(rotations, 270)
    return rotations[:MAX_FULL_FRAME_FAST_PASSES]


def build_full_frame_fast_scan_passes(image):
    return [
        {
            "stage": "fast_orientation",
            "rotation": rotation,
            "preprocess": "original",
            "angle_source": "cardinal_probe",
        }
        for rotation in detect_cardinal_rotation_order(image)
    ]


def add_unique_rotation(rotations, rotation):
    rotation = normalized_small_angle(rotation)
    if abs(rotation) < ANGLE_PROBE_MIN_ABS:
        return

    for existing in rotations:
        delta = abs(normalized_small_angle(existing - rotation))
        if delta <= ANGLE_PROBE_DUPLICATE_TOLERANCE:
            return

    rotations.append(rotation)


def build_angle_probe_passes(image, stage, include_fixed_45=True):
    rotations = []

    for rotation in detect_skew_probe_rotations(image):
        add_unique_rotation(rotations, rotation)

    if include_fixed_45:
        add_unique_rotation(rotations, 45)
        add_unique_rotation(rotations, -45)

    return [
        {
            "stage": stage,
            "rotation": rotation,
            "preprocess": "original",
            "angle_source": "auto_or_45",
        }
        for rotation in rotations[:ANGLE_PROBE_MAX_PASSES]
    ]


def preprocess_image(image, preprocess):
    if preprocess == "grayscale":
        return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return image


def prepare_image_for_ocr(image, source):
    height, width = image.shape[:2]
    source = (source or "unknown").lower()
    aspect = height / max(width, 1)

    if source == "image":
        min_width = MIN_IMAGE_OCR_WIDTH
        min_height = MIN_IMAGE_OCR_HEIGHT
        max_upscale = 1 if aspect > 1.7 and height > 900 else MAX_IMAGE_UPSCALE
        max_long_side = MAX_IMAGE_LONG_SIDE
        max_pixels = MAX_IMAGE_PIXELS
    elif source == "full_frame":
        min_width = MIN_FULL_FRAME_OCR_WIDTH
        min_height = MIN_FULL_FRAME_OCR_HEIGHT
        max_upscale = MAX_FULL_FRAME_UPSCALE
        max_long_side = MAX_FULL_FRAME_LONG_SIDE
        max_pixels = MAX_FULL_FRAME_PIXELS
    else:
        min_width = MIN_CROP_OCR_WIDTH
        min_height = MIN_CROP_OCR_HEIGHT
        max_upscale = MAX_CROP_UPSCALE
        max_long_side = MAX_CROP_LONG_SIDE
        max_pixels = MAX_CROP_PIXELS

    pixel_count = max(width * height, 1)
    downscale = min(
        max_long_side / max(width, height),
        (max_pixels / pixel_count) ** 0.5,
        1,
    )

    if downscale < 1:
        scale = downscale
        resize_reason = "downscale"
    else:
        scale = max(min_width / max(width, 1), min_height / max(height, 1), 1)
        scale = min(scale, max_upscale)
        resize_reason = "upscale" if scale > 1 else "none"

    if scale == 1:
        return image, {
            "source": source,
            "original_width": width,
            "original_height": height,
            "ocr_width": width,
            "ocr_height": height,
            "upscale": 1,
            "resize": resize_reason,
        }

    resized = cv2.resize(
        image,
        (round(width * scale), round(height * scale)),
        interpolation=cv2.INTER_CUBIC,
    )
    ocr_height, ocr_width = resized.shape[:2]

    return resized, {
        "source": source,
        "original_width": width,
        "original_height": height,
        "ocr_width": ocr_width,
        "ocr_height": ocr_height,
        "upscale": round(scale, 2),
        "resize": resize_reason,
    }