cvproject / scanner.py
sompimnara's picture
Upload 7 files
a1916d2 verified
import cv2
import numpy as np
from utils import (convolution2d, gaussian_kernel, sobel_edge_detection,
manual_threshold, manual_dilation, four_point_transform)
def scan_document(image_path):
# --- 1. การเตรียมข้อมูลภาพ ---
# ใช้ภาพถ่ายเอกสาร ปรับขนาดเพื่อให้ประมวลผลไว (Convolution กินแรงเครื่องมาก)
image = cv2.imread(image_path)
if image is None:
raise FileNotFoundError(f"ไม่พบไฟล์: {image_path}")
# Resize ให้ความสูงไม่เกิน 500px เพื่อให้ Convolution ทำงานทันใจ
ratio = image.shape[0] / 500.0
orig = image.copy()
image = cv2.resize(image, (int(image.shape[1] / ratio), 500))
# --- 2. การเตรียมภาพก่อนประมวลผล (Preprocessing) ---
# แปลงเป็น Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ลดสัญญาณรบกวน (Smoothing) โดยใช้ Convolution + Gaussian Kernel (เขียนเอง)
# สร้าง Kernel ขนาด 5x5
kernel_blur = gaussian_kernel(size=5, sigma=1.0)
blurred = convolution2d(gray, kernel_blur)
blurred = blurred.astype(np.uint8) # แปลงกลับเป็นรูปภาพ 8-bit
# --- 3. การตรวจจับขอบภาพ (Edge Detection) ---
# ใช้ Sobel Operator (เขียนเอง) แทน Canny
edges = sobel_edge_detection(blurred)
# แปลงเป็น Binary ด้วย Threshold (เขียนเอง)
# ค่า Threshold 50-100 ต้องลองจูนดูว่าค่าไหนเห็นขอบชัดสุด
binary_edges = manual_threshold(edges, thresh_value=50)
# --- 4. การตรวจจับขอบเขตเอกสาร ---
# Optional: ใช้ Morphology (Dilation) (เขียนเอง) เพื่อเชื่อมเส้นขอบที่ขาด
dilated_edges = manual_dilation(binary_edges, kernel_size=3)
# ค้นหา Contours (ส่วนนี้ใช้ OpenCV เพราะเขียนเองยากและช้ามาก)
contours, _ = cv2.findContours(dilated_edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
doc_contour = None
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# เลือกบริเวณที่มีลักษณะสี่เหลี่ยม (มีจุดมุม 4 จุด)
if len(approx) == 4:
doc_contour = approx
break
if doc_contour is None:
print("ไม่พบขอบกระดาษ ใช้ภาพต้นฉบับแทน")
return orig
# --- 5. การจัดเรียงจุดมุมเอกสาร ---
# เรียกใช้ใน four_point_transform ของ utils.py แล้ว
# คูณ ratio กลับ เพื่อให้ได้พิกัดบนภาพต้นฉบับ (Original Size)
doc_contour_original = doc_contour.reshape(4, 2) * ratio
# --- 6. การแปลงมุมมองภาพ (Perspective Transform) ---
# ปรับภาพให้เป็นสี่เหลี่ยมผืนผ้า (Bird's eye view) -> อันนี้คือภาพสี
warped_color = four_point_transform(orig, doc_contour_original)
# --- 7. การเตรียมภาพสำหรับโหมดต่างๆ ---
# สร้างเวอร์ชันขาว-ดำ (B&W) เตรียมไว้ด้วย (ใช้ Otsu เพื่อความคมชัดที่สุด)
warped_gray = cv2.cvtColor(warped_color, cv2.COLOR_BGR2GRAY)
_, warped_bw = cv2.threshold(warped_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# === จุดที่แก้ไข: คืนค่ากลับไปทั้ง 2 แบบ ===
# คืนค่า (ภาพสีที่ดัดแล้ว, ภาพขาวดำที่ทำ threshold แล้ว)
return warped_color, warped_bw