当前位置:首页 >> 脚本专栏

Opencv 图片的OCR识别的实战示例

一、图片变换

0、导入模块

导入相关函数,遇到报错的话,直接pip install 函数名。

import numpy as np
import argparse
import cv2

参数初始化

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
  help = "Path to the image to be scanned") 
args = vars(ap.parse_args())

Parameters:

--image images\page.jpg

1、重写resize函数

def 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 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, interpolation=inter)
  return resized

2、预处理

读取图片后进行重置大小,并计算缩放倍数;进行灰度化、高斯滤波以及Canny轮廓提取

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)

3、边缘检测

检测轮廓并排序,遍历轮廓。

cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]# 轮廓检测
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]#保留前5个轮廓

# 遍历轮廓
for c in cnts:
  # 计算轮廓近似
  peri = cv2.arcLength(c, True)# 计算轮廓长度,C表示输入的点集,True表示轮廓是封闭的
  #(C表示输入的点集,epslion判断点到相对应的line segment 的距离的阈值,曲线是否闭合的标志位)
  approx = cv2.approxPolyDP(c, 0.02 * peri, True)

  # 4个点的时候就拿出来
  if len(approx) == 4:
   screenCnt = approx
   break

4、透视变换

画出近似轮廓,透视变换,二值处理

cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
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)

二、OCR识别

0、安装tesseract-ocr

链接: 下载

在环境变量、系统变量的Path里面添加安装路径,例如:E:\Program Files (x86)\Tesseract-OCR

tesseract -v#打开命令行,进行测试
tesseract XXX.png result#得到结果 
pip install pytesseract#安装依赖包

打开python安装路径里面的python文件,例如C:\ProgramData\Anaconda3\Lib\site-packages\pytesseract\pytesseract.py
将tesseract_cmd 修改为绝对路径即可,例如:tesseract_cmd = ‘C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

1、导入模块

from PIL import Image
import pytesseract
import cv2
import os

2、预处理

读取图片、灰度化、滤波

image = cv2.imread('scan.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray, 3)

3、输出结果

filename = "{}.png".format(os.getpid())
cv2.imwrite(filename, gray)  
text = pytesseract.image_to_string(Image.open(filename))
print(text)
os.remove(filename)