项目实战——文档扫描OCR识别

扫描全能王的实现,maybe

目录

一、文档扫描

1、引入所需要的库

 2、图像的读取与预处理

读取图像

图像reszie,

 图像灰度化、滤波、边缘检测。

 3、轮廓检测

 4、透视与二值变换

二、文字识别


一、文档扫描

文档扫描所实现的功能如下图所示,左侧为原始图像,右侧为扫描后的图像。

1、引入所需要的库

import numpy as np
import argparse
import cv2
import matplotlib.pyplot as plt

def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
def plt_show(img):
    b, g, r = cv2.split(img)
    res = cv2.merge([r, g, b])
    plt.imshow(res)
    

 2、图像的读取与预处理


原始项目的源码中使用了ArgumentParser对象编辑,在运行程序前还需要设置edit configuration中的Paramerter参数,在这里我们直接使用设定一字典。

# 设置args参数,这里我们直接用字典表示
args = {'image': 'images\\page.jpg'}

读取图像

# 读取输入
image = cv2.imread(args['image'])
plt_show(image)

图像reszie,

因为原图尺寸比较大,所以我们先将图片resize比较小的尺寸,在这里我们预设resize后的图片的height为500.

# 图像resize
ratio = image.shape[0] / 500.0
orig = image.copy()
image = resize(orig, height=500)
plt_show(image)

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 = (wigth, int(h*r))
        
    resized = cv2.resize(image, dim, interpolation=inter)
    return resized

这里需要定义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 = (wigth, int(h*r))
        
    resized = cv2.resize(image, dim, interpolation=inter)
    return resized

 图像灰度化、滤波、边缘检测。

灰度化和滤波操作不必多说,进行边缘检测的目的是为下一步的轮廓检测做准备。

# 灰度化、滤波、边缘检测
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)

# 展示预处理结果
print("STEP 1: 边缘检测")
plt_show(image)

plt.imshow(edged, cmap='gray')

 3、轮廓检测

使用cv2.findContours()函数进行轮廓检测,并进行轮廓排序

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表示输入的点集
    # epslion表示原始轮廓到近似轮廓的最大距离,它是一个准确度参数
    # 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)
plt_show(image)

 4、透视与二值变换

这里我们定义了four_point_transform()函数


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 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
# 透视变换
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
plt_show(warped)

 二值处理

# 二值处理
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1]
plt.imshow(warped, cmap='gray')

 

二、文字识别

使用tesseract-ocr进行文字识别,这个有时间再补充。

  • 3
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值