文档扫描OCR识别项目|含代码【DataWhale项目|OpenCV】

参考课程:Opencv计算机视觉实战(Python版).

基本材料准备

  1. 一张含有字体的文档的图片即可。
    图片

思路介绍

1 从图片中剪切并变换为规整的矩形的文字图片

  1. 经常要对一个分辨率大的图像进行resize操作,理由是,为了能够在实验过程中能够在屏幕大小范围内看到整个图像的变化。比如实验的图像像素为2448×3264。而电脑屏幕是1920×1080。除此之外,resize操作一旦启用,且最后展示如果需要后期得到的某种用途的坐标集合(比如轮廓Contours)与原图的结合,就需要配合计算出ratio,并在结合的时候用到。
  2. image = resize(orig, height = 500)这里将调用cv2.resize方法时可能出现的异常情况的处理代码(if else)封装起来。这样当其他项目用到类似的操作时,只需要将函数copy过去,就可以。
  3. 对于图片处理的经典操作:转化为灰度图、高斯滤波去除输入图像的噪音(上一个项目信用卡数字识别,应该也是可以的)、Canny边缘检测、轮廓检测、特定轮廓过滤(这里为了得到最外界的边框通过对各边框的周长大小排序得到)、轮廓近似处理(确保将传入的不太规则的图片的轮廓近似为一个矩形,以进行周长、面积等计算操作)、轮廓内图像规整变换(由倾斜状态变换为方正的状态),其中规整变换涉及到繁琐的数学计算。暂不讲解。

2 安装pytesseract

  1. 该网址 下载类似这样格式名字的文件“tesseract-ocr-setup-4.00.00dev.exe”并安装,其中安装路径“PATH1”要记下。
  2. 将安装路径添加到环境变量中。此时打开命令终端,输入:tesseract -v 测试,显示版本号则表示安装成功。
  3. 在所用python版本下pip 安装:pip install pytesseract
  4. 然后打开该python版本对应下的Lib\site-packages中 叫pytesseract的文件夹。编辑文件夹下的pytesseract.py文件。ctrl+F搜索“tesseract_cmd = '”这样的一行代码,将其值修改为pytesseract安装文件的绝对路径。即在PATH1后再加上pytesseract.exe。即:tesseract_cmd = 'P:/pythonappsetup/Tesseract-OCR/tesseract.exe'。如此即可。

3 OCR过程

  1. 光学识别字符的过程就不赘述了,全在一句代码pytesseract.image_to_string

代码实现

  1. 规整变换图片的代码
# 导入工具包
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())

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 rect

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

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

def cv_show(name,img):
	cv2.imshow(name,img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

# 读取输入
image = cv2.imread("./images/page.jpg")
# cv_show("image_original",image)
#坐标也会相同变化
# 因为接下来会做resize操作,而如果要像在原图上得到反映,就需要知晓这个resize比例。
# 而之所以resize是因为如果原图展开,在电脑上展示会非常大,不能看到整体。但是我也在想是不是可以在实际生产中,可以去掉这一步!!!??
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)[1]
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

# 遍历轮廓
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 = approx
		break

# 展示结果
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)
  1. 检测图片中的文字过程
from PIL import Image
import pytesseract
import cv2
import os

preprocess = '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)                                   

个人问题

  1. 对比信用卡数字识别项目中的处理,为什么信用卡的项目没有用到Canny边缘检测?
  2. 整体来看,难点在于对于检测出的纸张的轮廓区域如何规整成为一个矩形的处理过程。具体来说就是定义的那两个函数four_point_transformorder_points

=============================== T H E E N D ! =================================================

猜你喜欢

转载自blog.csdn.net/m0_38052500/article/details/106905849