File size: 8,507 Bytes
efd3c0f | 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 | """
OCR ๅๅฆ็ใขใธใฅใผใซ
ๆฑใใ็ปๅใปในใญใฃใณๆๆธใฎ OCR ็ฒพๅบฆใ้ซใใใใใฎๅๅฆ็ใใคใใฉใคใณใจใ
PDF ใ PIL Image ใชในใใซๅคๆใใๆฉ่ฝใๆไพใใใ
ไฝฟใๆน๏ผใคใณใใผใไพ๏ผ:
from preprocess import load_input_images, apply_preprocess
pages = load_input_images(Path("scan.pdf")) # PDF โ 1ใใผใธ1ๆใฎใชในใ
pages = load_input_images(Path("photo.webp")) # ็ปๅ โ [1ๆ]
cleaned = apply_preprocess(pages[0], config={"deskew": True, "denoise": True})
ๅๅฆ็ในใใใ๏ผYAML ใฎ preprocess ใปใฏใทใงใณใงๅ ON/OFF ๅฏ่ฝ๏ผ:
deskew : ๅพใ่ฃๆญฃ๏ผHough ๅคๆ๏ผ
denoise : ใใคใบ้คๅป๏ผใใคใฉใใฉใซใใฃใซใฟ๏ผ
enhance_contrast : ใณใณใใฉในใๅผท่ชฟ๏ผCLAHE / LAB ่ฒ็ฉบ้๏ผ
sharpen : ใทใฃใผใๅ๏ผUnsharp Masking๏ผ
"""
from __future__ import annotations
from pathlib import Path
import cv2
import fitz # PyMuPDF
import numpy as np
from PIL import Image
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# PDFใป็ปๅใฎ่ชญใฟ่พผใฟ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
#: PDF ใฉในใฟใฉใคใบๆใฎ่งฃๅๅบฆใ200 dpi ไปฅไธใ OCR ใซๆจๅฅจใใใใ
PDF_DPI = 200
#: ๅฏพๅฟใใ็ปๅๆกๅผตๅญ
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif"}
def load_pdf_pages(pdf_path: Path, dpi: int = PDF_DPI) -> list[Image.Image]:
"""PDF ใฎๅ
จใใผใธใ PIL Image ใฎใชในใใซๅคๆใใใ
Args:
pdf_path: PDF ใใกใคใซใฎใใน
dpi: ใฉในใฟใฉใคใบ่งฃๅๅบฆ๏ผ้ซใใปใฉ้ซ็ฒพๅบฆใ ใใกใขใชใๆถ่ฒป๏ผ
Returns:
list[Image.Image]: 1 ่ฆ็ด = 1 ใใผใธใฎ RGB ็ปๅใชในใ
"""
doc = fitz.open(str(pdf_path))
mat = fitz.Matrix(dpi / 72, dpi / 72)
pages: list[Image.Image] = []
for page in doc:
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
pages.append(img)
doc.close()
return pages
def load_input_images(path: Path) -> list[Image.Image]:
"""็ปๅใพใใฏ PDF ใ่ชญใฟ่พผใฟใPIL Image ใฎใชในใใ่ฟใใ
PDF ใฎๅ ดๅใฏใใผใธใใจใซ 1 ่ฆ็ด ใ็ปๅใฎๅ ดๅใฏ [1 ่ฆ็ด ] ใ่ฟใใ
Args:
path: ๅ
ฅๅใใกใคใซใฎใใน๏ผPDF ใพใใฏ็ปๅ๏ผ
Returns:
list[Image.Image]: ใใผใธ๏ผใพใใฏ็ปๅ๏ผใใจใฎ RGB ็ปๅใชในใ
Raises:
ValueError: ๅฏพๅฟใใฆใใชใๆกๅผตๅญใๆๅฎใใใๅ ดๅ
"""
suffix = path.suffix.lower()
if suffix == ".pdf":
return load_pdf_pages(path)
if suffix in IMAGE_EXTENSIONS:
return [Image.open(path).convert("RGB")]
raise ValueError(f"ๅฏพๅฟใใฆใใชใใใกใคใซๅฝขๅผใงใ: {suffix}")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅ
้จใฆใผใใฃใชใใฃ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _to_bgr(pil_image: Image.Image) -> np.ndarray:
"""PIL Image (RGB) โ OpenCV BGR ndarray ใซๅคๆใใใ"""
return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
def _to_pil(bgr: np.ndarray) -> Image.Image:
"""OpenCV BGR ndarray โ PIL Image (RGB) ใซๅคๆใใใ"""
return Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅๅฆ็ในใใใ๏ผๅ้ขๆฐใฏ BGR ndarray ใๅใๅใ BGR ndarray ใ่ฟใ๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _deskew(bgr: np.ndarray) -> np.ndarray:
"""Hough ๅคๆใงๆๆธใฎๅพใใๆคๅบใใฆๅ่ปข่ฃๆญฃใใใ
ในใญใฃใใๆๆใกๆฎๅฝฑใงๅพใใๆๆธใ่ชๅใงใพใฃใใใซใใใ
ๅพใ่งใ 0.3 ๅบฆๆชๆบใฎๅ ดๅใฏ่ฃๆญฃใในใญใใใใใ
Args:
bgr: ๅ
ฅๅ็ปๅ (BGR ndarray)
Returns:
np.ndarray: ๅพใ่ฃๆญฃๅพใฎ็ปๅ
"""
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9, 9), 0)
edges = cv2.Canny(blur, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=150)
if lines is None:
return bgr
angles: list[float] = []
for line in lines:
theta = float(line[0][1])
angle = (theta * 180.0 / np.pi) - 90.0
if abs(angle) < 45.0:
angles.append(angle)
if not angles:
return bgr
median_angle = float(np.median(angles))
if abs(median_angle) < 0.3:
return bgr
h, w = bgr.shape[:2]
M = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), median_angle, 1.0)
return cv2.warpAffine(
bgr, M, (w, h),
flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REPLICATE,
)
def _denoise(bgr: np.ndarray) -> np.ndarray:
"""ใใคใฉใใฉใซใใฃใซใฟใงใใคใบใ้คๅปใใชใใใจใใธ๏ผๆๅญ่ผช้ญ๏ผใไฟ่ญทใใใ
ใฌใฆใทใขใณใใฉใผใจ้ใใใจใใธใไฟใกใชใใใใคใบใ ใใๅนณๆปๅใใใ
Args:
bgr: ๅ
ฅๅ็ปๅ (BGR ndarray)
Returns:
np.ndarray: ใใคใบ้คๅปๅพใฎ็ปๅ
"""
return cv2.bilateralFilter(bgr, d=9, sigmaColor=75, sigmaSpace=75)
def _enhance_contrast(bgr: np.ndarray) -> np.ndarray:
"""CLAHE๏ผๅถ้ไปใ้ฉๅฟใในใใฐใฉใ ๅนณๅฆๅ๏ผใงๅฑๆใณใณใใฉในใใๅผท่ชฟใใใ
็
งๆใ ใฉใใใ็ปๅใงใๆๅญใๅไธใซๆ็ญใซใชใใ
LAB ่ฒ็ฉบ้ใฎๆๅบฆใใฃใณใใซ (L) ใฎใฟใซ้ฉ็จใใ่ฒ็ธใฏๅคๅใใใชใใ
Args:
bgr: ๅ
ฅๅ็ปๅ (BGR ndarray)
Returns:
np.ndarray: ใณใณใใฉในใๅผท่ชฟๅพใฎ็ปๅ
"""
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
l_ch, a_ch, b_ch = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_enhanced = clahe.apply(l_ch)
return cv2.cvtColor(cv2.merge([l_enhanced, a_ch, b_ch]), cv2.COLOR_LAB2BGR)
def _sharpen(bgr: np.ndarray) -> np.ndarray:
"""Unsharp Masking ใงๆๅญใฎใจใใธใๅผท่ชฟใใฆใทใฃใผใใซใใใ
ใผใใใ็ปๅใในใญใฃใณๅพใฎใฝใใใในใ่ฃๆญฃใใใ
Args:
bgr: ๅ
ฅๅ็ปๅ (BGR ndarray)
Returns:
np.ndarray: ใทใฃใผใๅๅพใฎ็ปๅ
"""
blurred = cv2.GaussianBlur(bgr, (0, 0), sigmaX=3)
return cv2.addWeighted(bgr, 1.5, blurred, -0.5, 0)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅๅฆ็ใใคใใฉใคใณ๏ผๅ
ฌ้้ขๆฐ๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def apply_preprocess(
pil_image: Image.Image,
config: dict | None = None,
) -> Image.Image:
"""OCR ๅๅฆ็ใใคใใฉใคใณใๅฎ่กใใฆ PIL Image ใ่ฟใใ
ๅในใใใใฏ config ใฎ True/False ใงๅๅฅใซ ON/OFF ใงใใใ
config ใ็็ฅใใๅ ดๅใฏใในใฆใฎๅๅฆ็ใๆๅนใซใชใใ
Args:
pil_image: ๅๅฆ็ๅฏพ่ฑกใฎ PIL Image (RGB)
config: ๅๅฆ็่จญๅฎ่พๆธใใญใผใจๆขๅฎๅคใฏไปฅไธใฎ้ใใ
- deskew (bool, default True): ๅพใ่ฃๆญฃ
- denoise (bool, default True): ใใคใบ้คๅป
- enhance_contrast (bool, default True): ใณใณใใฉในใๅผท่ชฟ
- sharpen (bool, default True): ใทใฃใผใๅ
Returns:
Image.Image: ๅๅฆ็ๆธใฟใฎ PIL Image (RGB)
Example:
>>> cleaned = apply_preprocess(img, {"deskew": True, "denoise": False})
"""
cfg = config or {}
bgr = _to_bgr(pil_image)
if cfg.get("deskew", True):
bgr = _deskew(bgr)
if cfg.get("denoise", True):
bgr = _denoise(bgr)
if cfg.get("enhance_contrast", True):
bgr = _enhance_contrast(bgr)
if cfg.get("sharpen", True):
bgr = _sharpen(bgr)
return _to_pil(bgr)
|