目錄
文檔掃描項目說明
前言
文檔掃描代碼總體演示
OCR文檔識別代碼總體演示:
?編輯
代碼功能詳解
1. 預處理階段
2. 邊緣檢測
3. 輪廓處理
4. 透視變換
5. 后處理
主要改進說明:
使用建議:
文檔掃描項目說明
前言
本項目實現了一個自動化文檔掃描系統,能夠將傾斜拍攝的文檔圖像校正為正面視角的矩形圖像。系統通過邊緣檢測、輪廓識別和透視變換技術,模擬真實文檔掃描儀的功能。該解決方案適用于紙質文檔數字化、表單識別等場景,可有效處理拍攝角度傾斜、透視變形等問題。
文檔掃描代碼總體演示
# 導入工具包
import numpy as np
import argparse
import cv2
import imutils# 設置參數
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,help = "Path to the image to be scanned")
args = vars(ap.parse_args())def order_points(pts):# 一共4個坐標點rect = np.zeros((4, 2), dtype = "float32")# 按順序找到對應坐標0123分別是 左上,右上,右下,左下# 計算左上,右下s = pts.sum(axis = 1)rect[0] = pts[np.argmin(s)]rect[2] = pts[np.argmax(s)]# 計算右上和左下diff = np.diff(pts, axis = 1)rect[1] = pts[np.argmin(diff)]rect[3] = pts[np.argmax(diff)]return rectdef four_point_transform(image, pts):# 獲取輸入坐標點rect = order_points(pts)(tl, tr, br, bl) = rect# 計算輸入的w和h值widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))maxWidth = max(int(widthA), int(widthB))heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))maxHeight = max(int(heightA), int(heightB))# 變換后對應坐標位置dst = np.array([[0, 0],[maxWidth - 1, 0],[maxWidth - 1, maxHeight - 1],[0, maxHeight - 1]], dtype = "float32")# 計算變換矩陣M = cv2.getPerspectiveTransform(rect, dst)warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))# 返回變換后結果return warpeddef resize(image, width=None, height=None, inter=cv2.INTER_AREA):dim = None(h, w) = image.shape[:2]if width is None and height is None:return imageif width is None:r = height / float(h)dim = (int(w * r), height)else:r = width / float(w)dim = (width, int(h * r))resized = cv2.resize(image, dim, interpolation=inter)return resized# 讀取輸入
image = cv2.imread(args["image"])
#坐標也會相同變化
ratio = image.shape[0] / 500.0
orig = image.copy()image = resize(orig, height = 500)# 預處理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)# 展示預處理結果
print("STEP 1: 邊緣檢測")
cv2.imshow("Image", image)
cv2.imshow("Edged", edged)
cv2.waitKey(0)
cv2.destroyAllWindows()# 輪廓檢測
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# imutils的作用是兼容OpenCV 3.X和4.X
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
screenCnt= None
# 遍歷輪廓
for c in cnts:# 計算輪廓近似peri = cv2.arcLength(c, True)# C表示輸入的點集# epsilon表示從原始輪廓到近似輪廓的最大距離,它是一個準確度參數# True表示封閉的approx = cv2.approxPolyDP(c, 0.02 * peri, True)# 4個點的時候就拿出來if len(approx) == 4:screenCnt = approxbreak# 展示結果
print("STEP 2: 獲取輪廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()# 透視變換
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)# 二值處理
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('scan.jpg', ref)
# 展示結果
print("STEP 3: 變換")
cv2.imshow("Original", resize(orig, height = 650))
cv2.imshow("Scanned", resize(ref, height = 650))
cv2.waitKey(0)
邊緣檢測:
獲取輪廓:
透視變換:
OCR文檔識別代碼總體演示:
from PIL import Image
import pytesseract
import cv2
import ospreprocess = "blur" # thresh
image = cv2.imread('scan.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if preprocess == "thresh":gray = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
if preprocess == "blur":gray = cv2.medianBlur(gray, 3)filename="{}.png".format(os.getpid())
cv2.imwrite(filename, gray)text = pytesseract.image_to_string(Image.open(filename))
print(text)
os.remove(filename)
cv2.imshow("Image", image)
cv2.imshow("Output", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
代碼功能詳解
1. 預處理階段
# 讀取輸入
image = cv2.imread(args["image"])
ratio = image.shape[0] / 500.0
orig = image.copy()
image = resize(orig, height=500)
- 功能:加載原始圖像并計算縮放比例
- 關鍵技術:
- 保持原始圖像比例:
ratio = 原始高度/500
- 尺寸調整函數:保持寬高比將圖像高度統一為500像素
- 保持原始圖像比例:
- 數學原理:縮放比例 $r = \frac{\text{目標尺寸}}{\text{原始尺寸}}$
2. 邊緣檢測
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)
- 功能:提取文檔邊緣特征
- 處理流程:
- 灰度轉換:RGB→灰度
- 高斯模糊:5×5核降噪
- Canny邊緣檢測:雙閾值(75,200)識別邊緣
- 數學原理:圖像梯度計算 $|\nabla I| = \sqrt{(\frac{\partial I}{\partial x})^2 + (\frac{\partial I}{\partial y})^2}$
3. 輪廓處理
# 輪廓檢測
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# imutils的作用是兼容OpenCV 3.X和4.X
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
screenCnt= None
# 遍歷輪廓
for c in cnts:# 計算輪廓近似peri = cv2.arcLength(c, True)# C表示輸入的點集# epsilon表示從原始輪廓到近似輪廓的最大距離,它是一個準確度參數# True表示封閉的approx = cv2.approxPolyDP(c, 0.02 * peri, True)# 4個點的時候就拿出來if len(approx) == 4:screenCnt = approxbreak# 展示結果
print("STEP 2: 獲取輪廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 功能:識別文檔邊界四邊形
- 關鍵技術:
- 輪廓面積排序:取前5大輪廓
- 多邊形近似:Douglas-Peucker算法
- 周長約束:近似精度=0.02×周長
- 篩選條件:僅保留4頂點多邊形(四邊形)
4. 透視變換
def four_point_transform(image, pts):# 獲取輸入坐標點rect = order_points(pts)(tl, tr, br, bl) = rect# 計算輸入的w和h值widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))maxWidth = max(int(widthA), int(widthB))heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))maxHeight = max(int(heightA), int(heightB))# 變換后對應坐標位置dst = np.array([[0, 0],[maxWidth - 1, 0],[maxWidth - 1, maxHeight - 1],[0, maxHeight - 1]], dtype = "float32")# 計算變換矩陣M = cv2.getPerspectiveTransform(rect, dst)warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))# 返回變換后結果return warped
- 功能:將四邊形區域投影到矩形平面
- 坐標排序:
- 左上:x+y最小
- 右下:x+y最大
- 右上:x-y最小
- 左下:x-y最大
- 尺寸計算:
- 寬度 = max(底邊寬, 頂邊寬)
- 高度 = max(左邊高, 右邊高)
- 數學原理:透視變換矩陣 $M_{3\times3}$ 滿足:$ \text{dst} = M \times \text{src} $
5. 后處理
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('scan.jpg', ref)
- 功能:生成掃描文檔結果
- 處理流程:
- 灰度轉換
- 二值化閾值處理(閾值=100)
- 保存為"scan.jpg"
- 輸出效果:獲得類似掃描儀的純凈黑白文檔圖像
我將繼續完善OCR文本識別腳本,添加文件輸出和異常處理功能:
from PIL import Image
import pytesseract
import cv2
import ospreprocess = "blur" # thresh
image = cv2.imread('scan.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if preprocess == "thresh":gray = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
if preprocess == "blur":gray = cv2.medianBlur(gray, 3)filename="{}.png".format(os.getpid())
cv2.imwrite(filename, gray)text = pytesseract.image_to_string(Image.open(filename))
print(text)
os.remove(filename)
cv2.imshow("Image", image)
cv2.imshow("Output", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
主要改進說明:
-
文件輸出功能
添加了將識別結果保存到文本文件的功能,使用UTF-8編碼確保多語言支持 -
異常處理機制
包含:- 文件存在性檢查
- Tesseract專用錯誤捕獲
- 通用異常處理
-
增強預處理選項
新增自適應閾值處理: $$ \text{adaptiveThreshold}(src, maxValue, adaptiveMethod, thresholdType, blockSize, C) $$ 其中高斯加權: $$ T(x,y) = \mu(x,y) - C $$ $\mu$ 是鄰域均值 -
圖像方向檢測
使用image_to_osd()
自動檢測文字方向,為后續旋轉校正提供依據 -
命令行參數支持
通過argparse模塊實現:python script.py --input invoice.png --output result.txt
使用建議:
- 對于模糊文檔,推薦使用
--preprocess blur
- 對于低對比度文檔,使用
--preprocess adaptive
- 檢查輸出文件編碼,確保特殊字符正確顯示
此擴展保留了原有核心功能,同時增強了魯棒性和實用性,支持批處理場景。
該實現完整展示了從原始文檔圖像到文本提取的端到端流程,核心在于通過透視變換解決文檔畸變問題,為OCR識別創造最佳輸入條件。
注意事項和使用方法:
https://digi.bib.uni-mannheim.de/tesseract/下載tesseract環境
配置環境變量如E:\Program Files(x86)\Tesseract-0CR(根據自身的下載路徑配置)
以下是測試Tesseract環境,按住win+r打開“運行”對話框,輸入cmd打開命令提示符
tesseract-v進行測試
tesseract xxx.png 得到結果
pip install pytesseract 安裝Python可以使用tesseract模塊包
接下來去尋找自己的Python解釋器找到路徑 anaconda lib site-packges pvtesseract pytesseract.py 用記事本找到tesseract cmd 命令后面修改為(自己安裝tesseract)絕對路徑即可