大家好,欢迎来到IT知识分享网。
项目:文档扫描OCR识别
文章目录
一.整体流程演示
1.边缘检测
下图右边是输入图像,左边是通过边缘检测后的输出图像。我们需要关注的是图片的主题而不是背景,我们需要识别到我们要检测的主题。
2.获取轮廓
基于轮廓检测的方法,得到需要识别的物体的轮廓
3.透视变化
将文档变换,去掉所有的背景信息,平移+旋转+翻转
4.OCR字符识别
分析图片中的字符信息,可以通过使用一些目前开源的工具包来实现。
二.文档轮廓提取实现
首先我们读取输入图像:
# 读取输入 image = cv2.imread(args["image"]) #坐标也会相同变化 ratio = image.shape[0] / 500.0 orig = image.copy() image = resize(orig, height = 500)
这里的ratio是我们变换的比例,orig是对于原图的复制。然后我们将原图的复制版本传入到resize函数中,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
这个函数的功能是通过我们指定的h(传入的height)来计算比例®是多少,基于比例来计算图像相应的w和h,最后通过w和h来进行resize操作,接下来就是一些常规的图像的预处理操作:
# 预处理 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200)
1.转成灰度图,2.高斯滤波操作去除噪声点,剔除干扰项,3.检测边缘,通过边缘检测函数。接下来可以展示一下我们边缘检测的结果:
# 展示预处理结果 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]
观察上图,我们知道,一个图像是有很多轮廓的,一般情况下都是一个很大的轮廓,包含着一些小轮廓。所以我们现在要做的是:1.寻找轮廓,2.对找到的轮廓依据关键字key的contourArea(面积)进行排序,得到前五个最大的轮廓。然后我们进行遍历轮廓。
# 遍历轮廓 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
approxPolyDP函数是对一些不完整的轮廓点进行近似。 0.02 * peri是epsilon。默认是长度的百分之二。我们如果近似后得到了一个矩形,那我们就可以把这个轮廓给提取出来了。使用screenCnt这个变量来得到我们轮廓的边缘信息。我们对结果进行展示:
# 展示结果 print("STEP 2: 获取轮廓") cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2) cv2.imshow("Outline", image) cv2.waitKey(0) cv2.destroyAllWindows()
下面是我们绘图后的展示结果,绿色的部分就是我们通过近似得到的图像的边缘信息的外框:
三.原始与变换坐标计算
我们需要知道的是上图的A,B,C,D四个点的坐标,还有我们的变换矩阵M。代码如下:
# 透视变换 warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
第一个参数是我们原始输入的图像,第二个参数是我们上图标注的A,B,C,D这四个点的坐标,每个点都包含(x,y)这两个维度。所以是4*2,这里为啥要 * ratio这个比例呢?因为我们的边缘信息是在resize之后的图像上得到的,但是我们的orig是原图,所以我们需要将这A,B,C,D四个点再还原回原图上去。接下来我们再去看看这个透视变换具体是怎么做的吧
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
输入的pts是我们的传入的A,B,C,D四个坐标,代码中的tl,tr,br,bl这四个变量是这四个坐标的解析。接下来我们需要计算h和w,这样就可以计算得到我们上图中的E,F,G,H这四个坐标啦!h和w的计算方法如下:因为并不能保证是矩阵,所以这里采取的是一个近似的计算方法,即:计算方法为根号下x的平方+y的平方。如果是标准的矩形,那么有x和y其中有一个值必为0。我们再去两组计算结果中最大值作为我们的h或者w即可。有了我们输入的四个点A,B,C,D,和我们输入的四个点E,F,G,H,我们就可以去算我们的变换矩阵M了。因为涉及到投影,这个矩阵是一个3*3的矩阵。这个矩阵我们是通过使用opencv的内置函数getPerspective接口来计算的,这个函数的计算原理是什么呢,这里可以简单说明一下:
最后,通过我们得到的变换矩阵M,对输入图像施加上,让输入图像上的所有点都进行变换,最后得到变换后的图像进行返回即可。变换完成后,我们再对变换后的图像进行了一次二值化处理:
# 二值处理 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)
四.tesseract-ocr安装配置
配置完毕后,我们就可以使用cmd来检验下这个包是不是好用的;此时我们在控制台上键入tesseract -v,如果可以正确显示版本信息,则说明我们安装成功了。
指令运行结束,我们在D盘打开result.txt文件,发现识别结果已经被保存下来了,而且识别的非常正确。
我们平时更多的是使用python程序来做,如果需要使用我们的python来使用这个包的话,还需要在你的annconda相关的环境中安装pip install pytesseract
这个包才可以。这里我们也是成功的安装上了。
五.文档扫描识别效果
注意这里不要再去使用window的路径分隔方式了,容易让计算机识别时产生歧义,这里我们采用的是Linux的路径分隔方式。这里修改完毕之后,我们就可以进入我们的pytorch进行代码编写了。接下来的代码是我们的OCR识别的代码:
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)
我们将之前处理好的图片读取进来,转换成一张灰度图,然后我们可以通过指定preprocess的值来进行一些滤波操作或者二值化操作。然后调用我们安装的包提供的接口即可:
text = pytesseract.image_to_string(Image.open(filename)) print(text) os.remove(filename)
将之前讲过的边缘检测,获取轮廓,变换这三个流程全部走一遍:
很可惜,当前并不支持中文。
六.完整代码
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 # 读取输入 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)[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)
2.OCR相关代码
# https://digi.bib.uni-mannheim.de/tesseract/ # 配置环境变量如E:\Program Files (x86)\Tesseract-OCR # tesseract -v进行测试 # tesseract XXX.png 得到结果 # pip install pytesseract # anaconda lib site-packges pytesseract pytesseract.py # tesseract_cmd 修改为绝对路径即可 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)
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/130056.html