File size: 22,655 Bytes
8672bad |
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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
# Epitext_Back/ai_modules/preprocessor_unified.py
# -*- coding: utf-8 -*-
"""
================================================================================
Unified Image Preprocessing Module for Epitext AI Project
================================================================================
๋ชจ๋๋ช
: preprocessor_unified.py (v1.0.0 - Production Ready)
์์ฑ์ผ: 2025-12-02
๋ชฉ์ : ํ์ ์ด๋ฏธ์ง๋ฅผ Swin Gray์ OCR์ฉ์ผ๋ก ๋์์ ์ ์ฒ๋ฆฌ
์ํ: Production Ready
ํต์ฌ ๊ธฐ๋ฅ:
ํ ๋ฒ์ ๋ ๊ฐ์ง ์ ์ฒ๋ฆฌ ์๋ฃ:
1. Swin Gray: ๊ทธ๋ ์ด ๋น์ด์งํ -> 3์ฑ๋ (์ ๋ณด ์์ค ์ต์)
2. OCR: ์ด์งํ -> 1์ฑ๋ (๋ช
ํํ ํ๋ฐฑ)
์๋ ๋ฐฐ๊ฒฝ ๋ณด์ฅ:
- Swin: ๋ฐ์๋ฐฐ๊ฒฝ (>=127)
- OCR: ํฐ๋ฐฐ๊ฒฝ + ๊ฒ์ ๊ธ์ (255/0)
ํ๋ณธ ์๋ ๊ฒ์ถ: ํฐ ์ด๋์ด ์์ญ ์๋ณ
์์ญ ๊ฒ์ถ 1ํ: ํจ์จ์ฑ
์ค์ ํ์ผ ์ง์: JSON ๊ธฐ๋ฐ ์ปค์คํฐ๋ง์ด์ง
๋ก๊น
์ง์: DEBUG, INFO, WARNING, ERROR
์์กด์ฑ:
- opencv-python >= 4.8.0
- numpy >= 1.24.0
๋จ์ผ ํจ์:
preprocess_image_unified(input_path, output_swin_path, output_ocr_path, ...)
์ฌ์ฉ ์์:
>>> from ai_modules.preprocessor_unified import preprocess_image_unified
>>> result = preprocess_image_unified(
... "input.jpg",
... "swin.jpg",
... "ocr.png"
... )
================================================================================
"""
import cv2
import numpy as np
from pathlib import Path
import json
import logging
from typing import Dict, Optional, Tuple
# ================================================================================
# Logging Configuration
# ================================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - [%(levelname)s] %(message)s'
)
logger = logging.getLogger(__name__)
# ================================================================================
# Constants
# ================================================================================
# ๊ธฐ๋ณธ ์ค์ ๊ฐ
DEFAULT_MARGIN = 10
DEFAULT_BRIGHTNESS_THRESHOLD = 127
DEFAULT_RUBBING_MIN_AREA_RATIO = 0.1
DEFAULT_TEXT_MIN_AREA = 16
DEFAULT_TEXT_AREA_RATIO = 0.00005
DEFAULT_MORPHOLOGY_KERNEL_SIZE = (2, 2)
DEFAULT_MORPHOLOGY_CLOSE_ITERATIONS = 3
DEFAULT_MORPHOLOGY_OPEN_ITERATIONS = 2
DEFAULT_RUBBING_KERNEL_SIZE = (5, 5)
DEFAULT_RUBBING_CLOSE_ITERATIONS = 10
DEFAULT_RUBBING_OPEN_ITERATIONS = 5
# ================================================================================
# Main Preprocessing Class
# ================================================================================
class UnifiedImagePreprocessor:
"""
ํตํฉ ์ด๋ฏธ์ง ์ ์ฒ๋ฆฌ ํด๋์ค (Swin + OCR)
ํ ๋ฒ์ ์ฒ๋ฆฌ๋ก Swin Gray์ OCR์ฉ ์ด๋ฏธ์ง๋ฅผ ๋ชจ๋ ์์ฑํฉ๋๋ค.
Attributes:
config (dict): ์ ์ฒ๋ฆฌ ์ค์ ํ๋ผ๋ฏธํฐ
Example:
>>> prep = UnifiedImagePreprocessor()
>>> result = prep.preprocess_unified("input.jpg", "swin.jpg", "ocr.png")
"""
def __init__(self, config_path: Optional[str] = None) -> None:
"""
UnifiedImagePreprocessor ์ด๊ธฐํ
Args:
config_path (str, optional): ์ค์ ํ์ผ ๊ฒฝ๋ก (JSON)
"""
self.config = self._load_config(config_path)
logger.info("[INIT] UnifiedImagePreprocessor v1.0.0 ์ด๊ธฐํ ์๋ฃ")
def _load_config(self, config_path: Optional[str]) -> Dict:
"""์ค์ ํ์ผ ๋ก๋"""
default_config = {
"margin": DEFAULT_MARGIN,
"brightness_threshold": DEFAULT_BRIGHTNESS_THRESHOLD,
"rubbing_min_area_ratio": DEFAULT_RUBBING_MIN_AREA_RATIO,
"text_min_area": DEFAULT_TEXT_MIN_AREA,
"text_area_ratio": DEFAULT_TEXT_AREA_RATIO,
"morphology_kernel_size": DEFAULT_MORPHOLOGY_KERNEL_SIZE,
"morphology_close_iterations": DEFAULT_MORPHOLOGY_CLOSE_ITERATIONS,
"morphology_open_iterations": DEFAULT_MORPHOLOGY_OPEN_ITERATIONS,
"rubbing_kernel_size": DEFAULT_RUBBING_KERNEL_SIZE,
"rubbing_close_iterations": DEFAULT_RUBBING_CLOSE_ITERATIONS,
"rubbing_open_iterations": DEFAULT_RUBBING_OPEN_ITERATIONS,
}
# ๊ธฐ๋ณธ ์ค์ ํ์ผ ๊ฒฝ๋ก (config_path๊ฐ ์์ ๋)
if config_path is None:
default_config_path = Path(__file__).parent / "config" / "preprocess_config.json"
if default_config_path.exists():
config_path = str(default_config_path)
if config_path and Path(config_path).exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
user_config = json.load(f)
# _description ํ๋๋ ์ ์ธํ๊ณ ์
๋ฐ์ดํธ
user_config_clean = {k: v for k, v in user_config.items() if not k.startswith('_')}
default_config.update(user_config_clean)
logger.info(f"[CONFIG] ์ค์ ํ์ผ ๋ก๋: {config_path}")
except Exception as e:
logger.warning(f"[CONFIG] ์ค์ ํ์ผ ๋ก๋ ์คํจ: {e} - ๊ธฐ๋ณธ ์ค์ ์ฌ์ฉ")
return default_config
def _find_rubbing_bbox(self, gray_image: np.ndarray) -> Optional[Tuple[int, int, int, int]]:
"""
ํ๋ณธ ์์ญ ๊ฒ์ถ (ํฐ ์ด๋์ด ์ฌ๊ฐํ ์ฐพ๊ธฐ)
Args:
gray_image (np.ndarray): ๊ทธ๋ ์ด์ค์ผ์ผ ์ด๋ฏธ์ง
Returns:
tuple: (x, y, w, h) ๋๋ None
"""
H_img, W_img = gray_image.shape
# Step 1: ์ด๋์ด ์์ญ ์ถ์ถ
_, dark_mask = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV)
# Step 2: ๋ชจํด๋ก์ง ์ฐ์ฐ
kernel_rub = np.ones(self.config["rubbing_kernel_size"], np.uint8)
dark_mask = cv2.morphologyEx(
dark_mask, cv2.MORPH_CLOSE, kernel_rub,
iterations=self.config["rubbing_close_iterations"]
)
dark_mask = cv2.morphologyEx(
dark_mask, cv2.MORPH_OPEN, kernel_rub,
iterations=self.config["rubbing_open_iterations"]
)
# Step 3: ์ปจํฌ์ด ๊ฒ์ถ
contours, _ = cv2.findContours(dark_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
return None
# Step 4: ๊ฐ์ฅ ํฐ ์ปจํฌ์ด
largest = max(contours, key=cv2.contourArea)
area = cv2.contourArea(largest)
# Step 5: ๋ฉด์ ๊ฒ์ฆ
min_area = (H_img * W_img) * self.config["rubbing_min_area_ratio"]
if area < min_area:
return None
return cv2.boundingRect(largest)
def _find_text_bbox(self, gray_image: np.ndarray) -> Tuple[int, int, int, int]:
"""
ํ
์คํธ ์์ญ ๊ฒ์ถ
Args:
gray_image (np.ndarray): ๊ทธ๋ ์ด์ค์ผ์ผ ์ด๋ฏธ์ง
Returns:
tuple: (x, y, w, h)
"""
H_img, W_img = gray_image.shape
# Step 1: Otsu ์ด์งํ
_, binary = cv2.threshold(
gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
# Step 2: ๋ชจํด๋ก์ง ์ฐ์ฐ
kernel_morph = np.ones(self.config["morphology_kernel_size"], np.uint8)
binary = cv2.morphologyEx(
binary, cv2.MORPH_CLOSE, kernel_morph,
iterations=self.config["morphology_close_iterations"]
)
binary = cv2.morphologyEx(
binary, cv2.MORPH_OPEN, kernel_morph,
iterations=self.config["morphology_open_iterations"]
)
# Step 3: ์ปจํฌ์ด ๊ฒ์ถ
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Step 4: ์ต์ ๋ฉด์ ์ค์
min_area = max(
self.config["text_min_area"],
int((H_img * W_img) * self.config["text_area_ratio"])
)
# Step 5: ์ ํจํ ์ปจํฌ์ด ํํฐ๋ง
valid_contours = [
cnt for cnt in contours
if cv2.contourArea(cv2.boundingRect(cnt)) >= min_area
]
# Step 6: ๊ฒฝ๊ณ๋ฐ์ค ๊ณ์ฐ
if valid_contours:
all_points = np.vstack(valid_contours)
return cv2.boundingRect(all_points)
else:
return (0, 0, W_img, H_img)
def _apply_margin(
self,
bbox: Tuple[int, int, int, int],
gray_image: np.ndarray,
margin_val: int
) -> Tuple[int, int, int, int]:
"""์ฌ๋ฐฑ ์ถ๊ฐ"""
x, y, w, h = bbox
H_img, W_img = gray_image.shape
x_new = max(0, x - margin_val)
y_new = max(0, y - margin_val)
w_new = min(W_img - x_new, w + 2 * margin_val)
h_new = min(H_img - y_new, h + 2 * margin_val)
return (x_new, y_new, w_new, h_new)
def _ensure_bright_background(
self,
gray_cropped: np.ndarray
) -> Tuple[np.ndarray, Dict]:
"""
๋ฐ์๋ฐฐ๊ฒฝ ๋ณด์ฅ (Swin์ฉ)
Returns:
tuple: (์ฒ๋ฆฌ๋ ๊ทธ๋ ์ด ์ด๋ฏธ์ง, ์ฒ๋ฆฌ ์ ๋ณด)
"""
mean_brightness = np.mean(gray_cropped)
is_inverted = False
if mean_brightness < self.config["brightness_threshold"]:
gray_bright = cv2.bitwise_not(gray_cropped)
is_inverted = True
else:
gray_bright = gray_cropped.copy()
# ์ฌํ์ธ
final_brightness = np.mean(gray_bright)
if final_brightness < self.config["brightness_threshold"]:
gray_bright = cv2.bitwise_not(gray_bright)
is_inverted = not is_inverted
final_brightness = np.mean(gray_bright)
return gray_bright, {
"mean_brightness_before": float(mean_brightness),
"mean_brightness_after": float(final_brightness),
"is_inverted": is_inverted,
"is_bright_bg": final_brightness >= self.config["brightness_threshold"]
}
def _ensure_white_background(
self,
gray_cropped: np.ndarray
) -> Tuple[np.ndarray, Dict]:
"""
ํฐ๋ฐฐ๊ฒฝ ๋ณด์ฅ (OCR์ฉ)
Returns:
tuple: (์ฒ๋ฆฌ๋ ์ด์ง ์ด๋ฏธ์ง, ์ฒ๋ฆฌ ์ ๋ณด)
"""
# Step 1: ์ด์งํ
_, binary = cv2.threshold(
gray_cropped, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
# Step 2: ํด๋ผ๋ฆฌํฐ ํ๋จ
mean_brightness = np.mean(binary)
# Step 3: ํ์์ ๋ฐ์
if mean_brightness < self.config["brightness_threshold"]:
binary_final = cv2.bitwise_not(binary)
polarity = "inverted"
else:
binary_final = binary
polarity = "normal"
final_brightness = np.mean(binary_final)
return binary_final, {
"mean_brightness_before": float(mean_brightness),
"mean_brightness_after": float(final_brightness),
"polarity": polarity,
"is_white_bg": final_brightness > self.config["brightness_threshold"]
}
def preprocess_unified(
self,
input_image_path: str,
output_swin_path: str,
output_ocr_path: str,
margin: Optional[int] = None,
use_rubbing: bool = False
) -> Dict:
"""
ํตํฉ ์ ์ฒ๋ฆฌ (Swin Gray + OCR ๋์ ์์ฑ)
ํ ๋ฒ์ ํจ์ ํธ์ถ๋ก Swin Gray์ OCR์ฉ ์ด๋ฏธ์ง๋ฅผ ๋ชจ๋ ์์ฑํฉ๋๋ค.
ํ๋ณธ ๋ฐ ํ
์คํธ ์์ญ ๊ฒ์ถ์ 1ํ๋ง ์ํ๋์ด ํจ์จ์ฑ์ ๋ณด์ฅํฉ๋๋ค.
Args:
input_image_path (str): ์
๋ ฅ ์ด๋ฏธ์ง ๊ฒฝ๋ก
output_swin_path (str): Swin Gray ์ถ๋ ฅ ๊ฒฝ๋ก (JPG)
output_ocr_path (str): OCR ์ถ๋ ฅ ๊ฒฝ๋ก (PNG)
margin (int, optional): ํฌ๋กญ ์ฌ๋ฐฑ (ํฝ์
)
use_rubbing (bool): ํ๋ณธ ๊ฒ์ถ ์ฌ๋ถ (๊ธฐ๋ณธ: False)
Returns:
dict: ์ฒ๋ฆฌ ๊ฒฐ๊ณผ
์ฑ๊ณต ์: {
"success": True,
"original_shape": (H, W, C),
"bbox": (x, y, w, h),
"region_type": "text" or "rubbing",
"region_detected": bool,
"swin": {
"output_path": str,
"output_shape": (H, W, 3),
"is_bright_bg": bool,
...
},
"ocr": {
"output_path": str,
"output_shape": (H, W),
"is_white_bg": bool,
...
}
}
์คํจ ์: {
"success": False,
"message": str
}
Processing Steps:
1. ์ด๋ฏธ์ง ๋ก๋
2. ๊ทธ๋ ์ด์ค์ผ์ผ ๋ณํ
3. ์์ญ ๊ฒ์ถ (ํ๋ณธ ๋๋ ํ
์คํธ, 1ํ๋ง)
4. ํฌ๋กญ + ์ฌ๋ฐฑ
5. Swin Gray ์ฒ๋ฆฌ (๋ฐ์๋ฐฐ๊ฒฝ ๋ณด์ฅ)
6. OCR ์ฒ๋ฆฌ (์ด์งํ + ํฐ๋ฐฐ๊ฒฝ ๋ณด์ฅ)
7. ๋์ ์ ์ฅ
Output:
- Swin: JPG 3์ฑ๋ (๋น์ด์งํ 256๋จ๊ณ)
- OCR: PNG 1์ฑ๋ (์ด์งํ)
Example:
>>> prep = UnifiedImagePreprocessor()
>>> result = prep.preprocess_unified(
... "input.jpg",
... "swin.jpg",
... "ocr.png"
... )
>>> if result["success"]:
... swin_output = result["swin"]["output_path"]
... ocr_output = result["ocr"]["output_path"]
"""
margin_val = margin or self.config["margin"]
try:
# ====================================================================
# Step 1: ์ด๋ฏธ์ง ๋ก๋
# ====================================================================
img_bgr = cv2.imread(str(input_image_path), cv2.IMREAD_COLOR)
if img_bgr is None:
raise ValueError(f"์ด๋ฏธ์ง ๋ก๋ ์คํจ: {input_image_path}")
original_shape = img_bgr.shape
logger.info(f"[LOAD] ์ด๋ฏธ์ง ๋ก๋: {input_image_path} {original_shape}")
# ====================================================================
# Step 2: ๊ทธ๋ ์ด์ค์ผ์ผ ๋ณํ
# ====================================================================
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
# ====================================================================
# Step 3: ์์ญ ๊ฒ์ถ (ํ๋ณธ ๋๋ ํ
์คํธ)
# ====================================================================
if use_rubbing:
detected_bbox = self._find_rubbing_bbox(gray)
region_type = "rubbing"
logger.info("[DETECT] ํ๋ณธ ์์ญ ๊ฒ์ถ ๋ชจ๋")
else:
detected_bbox = None
region_type = "text"
logger.info("[DETECT] ํ
์คํธ ์์ญ ๊ฒ์ถ ๋ชจ๋")
H_img, W_img = gray.shape
# ====================================================================
# Step 4: ํฌ๋กญ + ์ฌ๋ฐฑ
# ====================================================================
if detected_bbox is not None:
bbox_final = self._apply_margin(detected_bbox, gray, margin_val)
logger.info(f"[DETECT] {region_type} ์์ญ ๊ฒ์ถ: {bbox_final}")
else:
# ํ๋ณธ ๋ฏธ๊ฒ์ถ ๋๋ ํ
์คํธ ๋ชจ๋ -> ํ
์คํธ ๊ฒ์ถ
if use_rubbing:
bbox_final = (0, 0, W_img, H_img)
logger.warning("[DETECT] ํ๋ณธ ๋ฏธ๊ฒ์ถ - ์ ์ฒด ์ด๋ฏธ์ง ์ฌ์ฉ")
else:
bbox_text = self._find_text_bbox(gray)
bbox_final = self._apply_margin(bbox_text, gray, margin_val)
logger.info(f"[DETECT] ํ
์คํธ ์์ญ ๊ฒ์ถ: {bbox_final}")
x, y, w, h = bbox_final
gray_cropped = gray[y:y+h, x:x+w]
logger.info(f"[CROP] ํฌ๋กญ ์๋ฃ: {gray_cropped.shape}")
# ====================================================================
# Step 5: Swin Gray ์ฒ๋ฆฌ
# ====================================================================
gray_bright, info_swin = self._ensure_bright_background(gray_cropped)
swin_output_3ch = cv2.cvtColor(gray_bright, cv2.COLOR_GRAY2BGR)
# ====================================================================
# Step 6: OCR ์ฒ๋ฆฌ
# ====================================================================
binary_final, info_ocr = self._ensure_white_background(gray_cropped)
# ====================================================================
# Step 7: ๋์ ์ ์ฅ
# ====================================================================
output_swin_path_obj = Path(output_swin_path)
output_swin_path_obj.parent.mkdir(parents=True, exist_ok=True)
swin_success = cv2.imwrite(str(output_swin_path_obj), swin_output_3ch)
output_ocr_path_obj = Path(output_ocr_path)
output_ocr_path_obj.parent.mkdir(parents=True, exist_ok=True)
ocr_success = cv2.imwrite(str(output_ocr_path_obj), binary_final)
if not swin_success or not ocr_success:
raise ValueError("์ด๋ฏธ์ง ์ ์ฅ ์คํจ")
logger.info(f"[SAVE] Swin ์ ์ฅ: {output_swin_path_obj}")
logger.info(f"[SAVE] OCR ์ ์ฅ: {output_ocr_path_obj}")
# ====================================================================
# ๊ฒฐ๊ณผ ๋ฐํ
# ====================================================================
return {
"success": True,
"version": "Unified Swin Gray + OCR (v1.0.0)",
"original_shape": original_shape,
"bbox": bbox_final,
"region_type": region_type,
"region_detected": detected_bbox is not None,
# Swin ๋ถ๋ถ
"swin": {
"output_path": str(output_swin_path_obj).replace("\\", "/"),
"output_shape": swin_output_3ch.shape,
"color_type": "Grayscale 3์ฑ๋ (B=G=R, ๋น์ด์งํ 256๋จ๊ณ)",
"is_inverted": info_swin["is_inverted"],
"mean_brightness_before": info_swin["mean_brightness_before"],
"mean_brightness_after": info_swin["mean_brightness_after"],
"is_bright_bg": info_swin["is_bright_bg"]
},
# OCR ๋ถ๋ถ
"ocr": {
"output_path": str(output_ocr_path_obj).replace("\\", "/"),
"output_shape": binary_final.shape,
"polarity": info_ocr["polarity"],
"mean_brightness_before": info_ocr["mean_brightness_before"],
"mean_brightness_after": info_ocr["mean_brightness_after"],
"is_white_bg": info_ocr["is_white_bg"]
},
"message": "[DONE] ํตํฉ ์ ์ฒ๋ฆฌ ์๋ฃ (Swin + OCR)"
}
except Exception as e:
logger.error(f"[ERROR] ํตํฉ ์ ์ฒ๋ฆฌ ์คํจ: {e}")
return {
"success": False,
"message": str(e)
}
# ================================================================================
# Global Instance & Convenience Functions
# ================================================================================
_global_preprocessor = None
def get_preprocessor(config_path: Optional[str] = None) -> UnifiedImagePreprocessor:
"""์ ์ญ ์ ์ฒ๋ฆฌ๊ธฐ ์ธ์คํด์ค ๋ฐํ"""
global _global_preprocessor
if _global_preprocessor is None:
_global_preprocessor = UnifiedImagePreprocessor(config_path)
return _global_preprocessor
def preprocess_image_unified(
input_path: str,
output_swin_path: str,
output_ocr_path: str,
margin: Optional[int] = None,
use_rubbing: bool = False
) -> Dict:
"""
ํธ์ ํจ์: ํตํฉ ์ ์ฒ๋ฆฌ
Args:
input_path (str): ์
๋ ฅ ์ด๋ฏธ์ง ๊ฒฝ๋ก
output_swin_path (str): Swin ์ถ๋ ฅ ๊ฒฝ๋ก
output_ocr_path (str): OCR ์ถ๋ ฅ ๊ฒฝ๋ก
margin (int, optional): ์ฌ๋ฐฑ
use_rubbing (bool): ํ๋ณธ ๋ชจ๋
Returns:
dict: ์ฒ๋ฆฌ ๊ฒฐ๊ณผ
"""
prep = get_preprocessor()
return prep.preprocess_unified(
input_path,
output_swin_path,
output_ocr_path,
margin,
use_rubbing
)
# ================================================================================
# Usage Example
# ================================================================================
if __name__ == "__main__":
"""
ํ
์คํธ ์์
"""
logger.info("=" * 80)
logger.info("[TEST] Unified Image Preprocessor v1.0.0 - ํ
์คํธ ์์")
logger.info("=" * 80)
try:
prep = UnifiedImagePreprocessor()
result = prep.preprocess_unified(
"test_input.jpg",
"test_swin.jpg",
"test_ocr.png"
)
if result["success"]:
logger.info("[TEST] ํตํฉ ์ ์ฒ๋ฆฌ ์ฑ๊ณต!")
logger.info(f"[TEST] Swin: {result['swin']['output_path']}")
logger.info(f"[TEST] OCR: {result['ocr']['output_path']}")
logger.info(f"[TEST] Swin ๋ฐ์๋ฐฐ๊ฒฝ: {'Yes' if result['swin']['is_bright_bg'] else 'No'}")
logger.info(f"[TEST] OCR ํฐ๋ฐฐ๊ฒฝ: {'Yes' if result['ocr']['is_white_bg'] else 'No'}")
else:
logger.error(f"[TEST] ์คํจ: {result['message']}")
except Exception as e:
logger.error(f"[TEST] ์์ธ: {e}")
logger.info("=" * 80)
|