學習Opencv+Python之檔案OCR
思路:
- 影像預處理獲取輪廓資訊
- 獲取照片中的角點構建變換矩陣
- 進行仿射變換矯正檔案視角
- 二值化提取文字資訊
代碼:
# 匯入工具包
import numpy as np
import cv2
# 獲取角點函式
def order_points(pts):
# 設定并初始化一個4行2列全為0的array,來存放四個角點
rect = np.zeros((4, 2), dtype = "float32")
# 對容器pts按行求和,即將坐標的x值和y值求和
s = pts.sum(axis = 1)
# 當x+y最小時,為左上角
rect[0] = pts[np.argmin(s)]
# 當x+y最大時,為右下角
rect[2] = pts[np.argmax(s)]
# 對容器pts按行求差,即將坐標的x值和y值求差
diff = np.diff(pts, axis = 1)
# 當差值最小時,即為右上角
rect[1] = pts[np.argmin(diff)]
# 當差值最小時,即為左下角
rect[3] = pts[np.argmax(diff)]
return rect
# 投射變換函式
def four_point_transform(image, pts):
# 獲取輸入坐標點
rect = order_points(pts)
(tl, tr, br, bl) = rect
# 計算距離
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[0]對應左上角,dst[1]對應右上角,dst[2]對應右下角,dst[3]對應左下角,注意影像的坐標原點是左上角
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype = "float32")
# 計算變換矩陣
## 投射變換,函式cv2.getPerspectiveTransform需提供四個坐標點
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
# 回傳變換后結果
return warped
# 指定輸出影像的大小,防止影像尺寸太大
def resize(image, width=None, height=None):
dim = None
#獲取影像的高、寬
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if 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, cv2.INTER_AREA)
return resized
# 讀取輸入
image = cv2.imread('1.jpg')
# 坐標也會相同變化
ratio = image.shape[0] / 500.0
# 復制影像
orig = image.copy()
# 指定影像高,自動獲取縮放比得到寬
image = resize(orig, height = 500)
# 第一步:預處理
# 轉換為灰度影像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 高斯濾波,高斯核大小為(5, 5)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
# 使用Canny算子獲取邊緣資訊
edged = cv2.Canny(gray, 75, 200)
print("STEP 1: 邊緣檢測")
cv2.imshow("Image", image)
cv2.imshow("Edged", edged)
# 輪廓檢測
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]
# 依據輪廓所圍的面積進行排序,并選取前六個,進行順時針標記
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
# 第二步:遍歷獲取輪廓
for c in cnts:
# 計算輪廓長度
peri = cv2.arcLength(c, True)
# 對輪廓進行多邊形擬合近似,原曲線到擬合多邊形的距離為d,若d小于(0.02*peri),則濾掉,否則保留
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# 當只需四邊形即能擬合時取出
if len(approx) == 4:
screenCnt = approx
break
# 展示結果
print("STEP 2: 獲取輪廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
# 第三步:透視變換
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
# 二值處理
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
_, ref = cv2.threshold(warped, 180, 255, cv2.THRESH_BINARY)
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)
結果:

注意:(代碼中的幾個自定義函式理解,大家可以用debug除錯一下即可理解)
- order_points():對于坐標(x, y),求 s = x + y 的值,當 s 最小時說明是左上的那個角,當 s 的值最大時為左上角的對角,類推,求坐標值的差,當差最小時為右上角,最大時為左下角;
- four_point_transform():對order_points()獲取的四個點組成的四邊形求邊長,那么轉換后的四個頂點為:

- resize():對于原始影像的高和寬(h, w),如果輸入的高為height,先求比例r = height / h, 而后即可獲得原始高寬比下的寬width,類推,指定寬同樣得到高,
注:此代碼是對唐宇迪博士Opencv實戰代碼的復現
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/297966.html
標籤:其他
上一篇:Run的流程和Docker原理
