OCR สำหรับเอกสารสแกน
ใช้ Tesseract ผ่าน pytesseract การเตรียมภาพล่วงหน้า และการปรับปรุงความแม่นยำ
OCR สำหรับเอกสารสแกน เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
เมื่อใดจึงจำเป็นต้องใช้ OCR
เอกสารไม่ได้เป็น PDF ที่สร้างจากข้อมูลดิจิทัลโดยกำเนิดทั้งหมด เอกสารที่สแกน ภาพถ่ายข้อความ บันทึกที่เขียนด้วยลายมือ และ PDF ที่ประกอบด้วยรูปภาพ จำเป็นต้องใช้ การรู้จำอักขระด้วยแสง (OCR) เพื่อแยกข้อความ
OCR แปลงภาพพิกเซลของข้อความให้เป็นอักขระที่เครื่องอ่านได้ ไลบรารีไพธอนชั้นนำสองรายการ ได้แก่ ไพเทสเซอร์แรคต์ (เทสเซอร์แรคต์ของกูเกิล) และ EasyOCR (การเรียนรู้เชิงลึก รองรับหลายภาษา)
พื้นฐานของไพเทสเซอร์แรคต์
ไพเทสเซอร์แรคต์เป็นตัวห่อหุ้มของไพธอนสำหรับกลไก OCR เทสเซอร์แรคต์ของกูเกิล ให้ติดตั้งเทสเซอร์แรคต์ก่อนในระดับ OS จากนั้นจึงใช้ pip install pytesseract Pillow
import pytesseract
from PIL import Image
# Simple text extraction
image = Image.open('scanned_document.png')
text = pytesseract.image_to_string(image)
print(text)
# Specify language (default: English)
text_fr = pytesseract.image_to_string(
Image.open('french_doc.png'),
lang='fra'
)
# Get detailed output with bounding boxes
data = pytesseract.image_to_data(
image,
output_type=pytesseract.Output.DICT
)
for i, word in enumerate(data['text']):
if word.strip():
conf = data['conf'][i]
print(f'Word: {word!r:20} Confidence: {conf}')การเตรียมภาพล่วงหน้า: ระดับสีเทา
ความแม่นยำของ OCR ขึ้นอยู่กับคุณภาพของภาพอย่างมาก ขั้นตอนแรกของการเตรียมภาพล่วงหน้าคือการแปลงเป็นระดับสีเทา สีจะเพิ่มสัญญาณรบกวนโดยไม่ช่วยให้รู้จำอักขระได้ดีขึ้น
ใช้พิลโลว์หรือ OpenCV สำหรับการเตรียมภาพล่วงหน้า ระดับสีเทาช่วยลดสัญญาณรบกวนและปรับปรุงการตรวจจับขอบเขตอักขระของเทสเซอร์แรคต์
from PIL import Image, ImageOps
import numpy as np
def preprocess_grayscale(image_path):
img = Image.open(image_path)
# Convert to grayscale
img = img.convert('L') # 'L' = 8-bit grayscale
# Optionally resize for better OCR (Tesseract works best at ~300 DPI)
# Scale up small images
width, height = img.size
if width < 800:
scale = 800 / width
new_size = (int(width * scale), int(height * scale))
img = img.resize(new_size, Image.LANCZOS)
return img
img = preprocess_grayscale('scan.jpg')
text = pytesseract.image_to_string(img)
print(text[:300])การเตรียมภาพล่วงหน้า: การกำหนดค่าเกณฑ์
การกำหนดค่าเกณฑ์จะแปลงภาพระดับสีเทาให้เป็นสีดำและขาวล้วน วิธีนี้จะลบเงาสีเทา แสงที่ไม่สม่ำเสมอ และสัญญาณรบกวนจากพื้นหลัง ทำให้ข้อความโดดเด่นอย่างชัดเจนสำหรับ OCR
from PIL import Image, ImageFilter
import numpy as np
def apply_threshold(img):
# Method 1: Simple fixed threshold
img_array = np.array(img)
threshold = 128
binary = np.where(img_array > threshold, 255, 0).astype(np.uint8)
return Image.fromarray(binary)
def adaptive_threshold(img):
# Method 2: Otsu's method via OpenCV (better for uneven lighting)
try:
import cv2
img_array = np.array(img)
_, binary = cv2.threshold(
img_array, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
return Image.fromarray(binary)
except ImportError:
return apply_threshold(img)
img = preprocess_grayscale('uneven_scan.png')
img_clean = adaptive_threshold(img)
text = pytesseract.image_to_string(img_clean)
print(text[:300])การเตรียมภาพล่วงหน้า: การแก้ภาพเอียง
เอกสารที่สแกนมักมีการหมุนเล็กน้อย แม้เอียงเพียง 2 องศาก็ลดความแม่นยำของ OCR ได้อย่างมาก การแก้ภาพเอียงจะตรวจจับและแก้ไขมุมการหมุนก่อนส่งภาพให้กลไก OCR
import numpy as np
from PIL import Image
def deskew(img):
try:
import cv2
img_array = np.array(img)
# Find rotation angle using Hough line transform
edges = cv2.Canny(img_array, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, threshold=100)
if lines is None:
return img # no lines detected, return unchanged
angles = []
for line in lines:
rho, theta = line[0]
angle = np.degrees(theta) - 90
if -45 < angle < 45:
angles.append(angle)
if not angles:
return img
median_angle = np.median(angles)
if abs(median_angle) > 0.5: # only deskew if significant tilt
print(f'Deskewing by {median_angle:.2f} degrees')
return img.rotate(-median_angle, expand=True, fillcolor=255)
return img
except ImportError:
return img # OpenCV not available — skip deskewตัวเลือกภาษาของเทสเซอร์แรคต์
เทสเซอร์แรคต์รองรับภาษามากกว่า 100 ภาษา ให้ดาวน์โหลดชุดภาษาด้วยตัวจัดการแพ็กเกจของ OS สำหรับเอกสารหลายภาษา ให้ระบุหลายภาษาด้วยตัวคั่น +
import pytesseract
from PIL import Image
# List available languages
import subprocess
result = subprocess.run(['tesseract', '--list-langs'], capture_output=True, text=True)
print('Available languages:')
print(result.stdout)
# Single language
text_en = pytesseract.image_to_string(Image.open('doc.png'), lang='eng')
# Multiple languages (auto-detect best match)
text_multi = pytesseract.image_to_string(
Image.open('doc.png'),
lang='eng+fra+deu' # English + French + German
)
# Tesseract config options for better accuracy
custom_config = r'--oem 3 --psm 6' # OEM 3=LSTM, PSM 6=assume uniform block of text
text_tuned = pytesseract.image_to_string(
Image.open('doc.png'),
config=custom_config
)EasyOCR: พื้นฐานการเรียนรู้เชิงลึก
EasyOCR ใช้โมเดลการเรียนรู้เชิงลึก และทำงานได้ดีกว่าเทสเซอร์แรคต์กับภาพที่เสื่อมคุณภาพ ข้อความโค้ง และอักษรที่ไม่ใช่ละติน โดยไม่ต้องติดตั้งในระดับ OS
ติดตั้งด้วย pip install easyocr การเรียกใช้ครั้งแรกจะดาวน์โหลดน้ำหนักโมเดลประมาณ 200 เมกะไบต์
import easyocr
# Initialize reader (downloads model on first run)
reader = easyocr.Reader(
['en', 'tr'], # list of languages
gpu=False # set True if CUDA available
)
# Read text from image
results = reader.readtext('scanned_page.png')
for (bbox, text, confidence) in results:
print(f'Text: {text!r:30} Confidence: {confidence:.2f}')
# bbox = [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] (four corners)
# Get plain text only
text_only = ' '.join(result[1] for result in results)
print('Full text:', text_only[:300])EasyOCR สำหรับเอกสารหลายภาษา
EasyOCR จัดการเอกสารที่มีหลายภาษาได้ดี เหมาะสำหรับสัญญาระหว่างประเทศ เอกสารงานวิจัยที่มีคำบรรยายหลายภาษา หรือเอกสารที่มีศัพท์เทคนิคในอักษรคนละชุด
import easyocr
# For Arabic-English mixed document
reader_ar = easyocr.Reader(['ar', 'en'], gpu=False)
results = reader_ar.readtext('arabic_contract.png')
# For CJK languages
reader_cjk = easyocr.Reader(['ch_sim', 'en'], gpu=False) # Simplified Chinese + English
results_cjk = reader_cjk.readtext('chinese_report.png')
# Filter by confidence threshold
HIGH_CONFIDENCE = 0.7
def filter_confident_results(results, threshold=HIGH_CONFIDENCE):
return [
(bbox, text, conf)
for bbox, text, conf in results
if conf >= threshold
]กระบวนการเตรียมภาพล่วงหน้าแบบครบถ้วน
เชื่อมขั้นตอนการเตรียมภาพล่วงหน้าทั้งหมด ได้แก่ การแปลงเป็นระดับสีเทา การกำหนดค่าเกณฑ์ และการแก้ภาพเอียง ให้เป็นฟังก์ชันกระบวนการเดียว เรียกใช้ OCR กับภาพที่ทำความสะอาดแล้ว และส่งคืนทั้งข้อความกับค่าความเชื่อมั่น
import pytesseract
from PIL import Image
def ocr_pipeline(image_path, lang='eng', engine='tesseract'):
print(f'Processing: {image_path}')
# 1. Load
img = Image.open(image_path)
# 2. Preprocess
img = img.convert('L') # grayscale
img = adaptive_threshold(img) # binarize
img = deskew(img) # correct rotation
# 3. OCR
if engine == 'easyocr':
reader = easyocr.Reader([lang], gpu=False)
results = reader.readtext(image_path)
text = ' '.join(r[1] for r in results if r[2] > 0.5)
else:
config = f'--oem 3 --psm 6 -l {lang}'
text = pytesseract.image_to_string(img, config=config)
# 4. Clean
text = '\n'.join(
line.strip() for line in text.splitlines()
if line.strip()
)
return text
text = ocr_pipeline('invoice_scan.jpg')
print(text[:500])การจัดการ PDF ที่ประกอบด้วยรูปภาพ
PDF บางไฟล์มีหน้าที่สแกนและจัดเก็บเป็นรูปภาพอยู่ภายในโครงสร้าง PDF ให้ตรวจจับ PDF ประเภทนี้ แล้วใช้ PyMuPDF แยกรูปภาพออกมาก่อนเพื่อใช้ OCR ทีละหน้า
import fitz
from PIL import Image
import io
import pytesseract
def is_image_pdf(doc):
# Check if first page has very little extractable text
text = doc[0].get_text().strip()
return len(text) < 50
def ocr_pdf(filepath):
doc = fitz.open(filepath)
if not is_image_pdf(doc):
# Native text — no OCR needed
return '\n'.join(doc[i].get_text() for i in range(len(doc)))
print('Image PDF detected — running OCR')
all_text = []
for page_num in range(len(doc)):
page = doc[page_num]
# Render page as image at 300 DPI
mat = fitz.Matrix(300/72, 300/72) # scale to 300 DPI
pix = page.get_pixmap(matrix=mat)
img = Image.open(io.BytesIO(pix.tobytes('png')))
text = pytesseract.image_to_string(img)
all_text.append(f'--- Page {page_num+1} ---\n{text}')
doc.close()
return '\n'.join(all_text)การกรองตามความเชื่อมั่นและการประมวลผลภายหลัง
ผลลัพธ์จาก OCR มีข้อผิดพลาด โดยเฉพาะกับภาพที่เสื่อมคุณภาพ ให้ประมวลผลข้อความภายหลังด้วยการกรองคำที่มีความเชื่อมั่นต่ำ แก้ข้อผิดพลาด OCR ที่พบบ่อย (0 กับ O, 1 กับ l) และปรับช่องว่างให้เป็นรูปแบบเดียวกัน
import re
COMMON_OCR_ERRORS = {
r'\b0([a-z])\b': r'O\1',
r'\bl([0-9])\b': r'1\1',
r'\|': 'I',
r' +': ' ',
}
def post_process_ocr(text):
for pattern, replacement in COMMON_OCR_ERRORS.items():
text = re.sub(pattern, replacement, text)
lines = [line.strip() for line in text.splitlines()]
return '\n'.join(line for line in lines if line)
def high_confidence_ocr(words_with_conf, min_confidence=60):
words = [w for w, conf in words_with_conf if w.strip() and conf >= min_confidence]
return post_process_ocr(' '.join(words))
fake_ocr_output = [('0range', 90), ('|s', 40), ('l5', 85), ('good', 95)]
print(high_confidence_ocr(fake_ocr_output))ตรวจสอบความรู้
การใช้ค่าเกณฑ์ (การทำให้เป็นไบนารี) กับภาพก่อนทำ OCR มีจุดประสงค์อะไร
ทบทวน: OCR สำหรับเอกสารที่สแกน
OCR แปลงภาพที่สแกนให้เป็นข้อความที่เครื่องอ่านได้ ไพเทสเซอร์แรคต์ เป็นตัวห่อหุ้มเทสเซอร์แรคต์ของกูเกิล ซึ่งรวดเร็วและผ่านการพัฒนามาอย่างดี พร้อมชุดภาษามากกว่า 100 ภาษา ส่วน EasyOCR ใช้การเรียนรู้เชิงลึก และจัดการภาพที่เสื่อมคุณภาพกับข้อความหลายภาษาได้ดีกว่า
ควรเตรียมภาพล่วงหน้าเสมอ โดยแปลงเป็นระดับสีเทา ใช้การกำหนดค่าเกณฑ์ของโอสึเพื่อทำให้เป็นไบนารี และแก้ภาพเอียงเพื่อแก้การหมุน สำหรับ PDF ที่ประกอบด้วยรูปภาพ ให้เรนเดอร์หน้าเป็นภาพที่มี DPI สูงด้วย PyMuPDF แล้วจึงทำ OCR กรองผลลัพธ์ตามค่าเกณฑ์ความเชื่อมั่นเพื่อไม่รวมสัญญาณรบกวน
คำถามที่พบบ่อย
บทเรียน “OCR สำหรับเอกสารสแกน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “OCR สำหรับเอกสารสแกน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “OCR สำหรับเอกสารสแกน”
ใช้ Tesseract ผ่าน pytesseract การเตรียมภาพล่วงหน้า และการปรับปรุงความแม่นยำ คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “OCR สำหรับเอกสารสแกน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การแยกวิเคราะห์ PDF ด้วย PyMuPDF และ pdfplumber
- OCR สำหรับเอกสารสแกน
- ตัวแทนถามตอบจากเอกสารหลายฉบับ
- การจำแนกและกำหนดเส้นทางเอกสาร