OCR应用
- 1 OCR读取账单
- 1.1 背景及思路
- 1.2 代码
1 OCR读取账单
1.1 背景及思路
-
思路
目标是读取图片中账单的信息。首先要截取图片上的账单,考虑到账单并非都是整齐摆放,为了保持算法的通用性,通过透视变换对扣取的账单摆正,然后调用工具识别账单上的信息。 -
步骤
1) 读取图像,做二值化。
2)开运算除噪声。
3)找到图像的最大外部轮廓,根轮廓得到账单的最小外接矩形的坐标,根据坐标对账单做透视变换。
4)识别账单上的信息。
1.2 代码
img_rgb = cv2.imread('OCR识别账单文字/note.jpg')
img_gray = cv2.imread('OCR识别账单文字/note.jpg', 0)
img = img_gray.copy()
_ ,benary = cv2.threshold(img_gray,0,240,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
plt.imshow(benary,"gray")
k=np.ones((10,10),np.uint8)
r1=cv2.morphologyEx(benary,cv2.MORPH_OPEN,k) # 除掉了噪声
plt.imshow(r1,"gray")
ret, binary = cv2.threshold(r1,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# ret, binary = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0])
points = cv2.boxPoints(rect)
points = points.astype(np.int32)
image=cv2.drawContours(img_rgb.copy(),[points],0,(255,255,255),2)
# 透视变换
pts = np.zeros((4, 2), np.float32)
res = np.sum(points, axis=1)
pts[0] = points[np.argmin(res)]
pts[2] = points[np.argmax(res)]
res = np.diff(points, axis=1)
pts[1] = points[np.argmin(res)]
pts[3] = points[np.argmax(res)]
pts = np.array(pts, np.float32)
#计算边长
w1 = np.sqrt((pts[0][0] - pts[1][0]) ** 2 + (pts[0][1] - pts[1][1]) ** 2)
w2 = np.sqrt((pts[2][0] - pts[3][0]) ** 2 + (pts[2][1] - pts[3][1]) ** 2)
w = int(max(w1, w2))
h1 = np.sqrt((pts[1][0] - pts[2][0]) ** 2 + (pts[1][1] - pts[2][1]) ** 2)
h2 = np.sqrt((pts[0][0] - pts[3][0]) ** 2 + (pts[0][1] - pts[3][1]) ** 2)
h = int(max(h1, h2))
#计算目标图像的尺寸
dst = np.array([
[0, 0],
[w - 1, 0],
[w - 1, h - 1],
[0, h - 1]
], np.float32)
#透视变换
mat = cv2.getPerspectiveTransform(pts, dst)
img = img_gray.copy()
img = cv2.warpPerspective(img, mat, (w, h))
plt.imshow(img,"gray")
# 二值化
img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
text = pytesseract.image_to_string(img)
print(text)
'''
Berghotel
Srosse Scheidegg
SBI Geindehald
Fate Rotter
Rech te A572 2.07. 2007/18:29:17
bar Tech Y/0t
Qieatta Macehial 4450 OF 9.00
‘ubloxt a 500 oF s.09
nGcheotnscettzel & 22.00 OF 2200
worsespstzt) 850 OF HEBD
Jorat: oF 54,56
Incl, 1.8% St $850.08: 3.85
Fntsprteht tn Euro $6.33. EUR
Es bedtente Sta: Ursuta
Tht Hee: 430-234 |
Tel. 088 853.67 16
Fax, : 088 858 87 19
Ennai ls srassesche angeBbiuevie.ch
'''
上图中左图为原图,右图为二值化后的图像,观察发现,二值化后的图像有噪声,影响寻找账单的轮廓。
对二值化后的图像做开运算可以消除图像上的噪声,方便寻找图像的轮廓,右图为
根据图像最外轮廓得到的账单,并对账单做透视变换的结果,根据右图可以做检测。