Opencv学习笔记(2)—文档扫描OCR识别

这一个好好做完笔记然后就可以自己想点小东西进行下实战测试咯!

第一步 图像预处理与边缘检测

在图象预处理时,把图象复制然后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
# 读取输入



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] # 取得前5各最大的轮廓

# 遍历轮廓
for c in cnts:
	# 计算轮廓近似
	peri = cv2.arcLength(c, True)
	# C表示输入的点集
	# epsilon表示从原始轮廓到近似轮廓的最大距离,它是一个准确度参数
	# True表示封闭的
	approx = cv2.approxPolyDP(c, 0.02 * peri, True) # 这个的意思是长度的2%

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

# 展示结果
print("STEP 2: 获取轮廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

第三步 透视转换

上一步中得到了最外轮廓,然后进行透视转换,使得不太规整的图片变得规整,效果如下图

变化前:

opennlp 实体识别 opencv ocr识别_Image


变化后:

opennlp 实体识别 opencv ocr识别_Image_02


这里就不说原理啦,有很多博客讲的;变换后把结果存储为图片,进行下一步OCR操作

# 透视变换实现函数
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


# 透视变换
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)

第四步 OCR操作

把上一步的结果读取进来,进行下滤波操作或者二值化操作,然后就使用pytesseract工具包进行图片转文字操作就行了

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)