Python构建一个文档扫描器的实现

您可能想要对文档进行数字化处理,以节省物理空间或创建备份。无论怎样,编写一个程序将纸质文件的照片转换成准格式正是Python所擅长的任务。

结合使用多个适当的库,您就可以构建一个小型应用程序对文档进行数字化处理。您的程序将以物理文档的图像作为输入,对其运用几种图像处理技术,即可输出输入的扫描版。

 

准备好环境

首先您应该熟悉Python的基础知识,还需要了解如何使用NumPy Python库。

打开任何Python IDE,创建两个Python文件。将一个命名为main.py,将另一个命名为transform.py。然后在终端上执行以下命令,安装所需的库。

pip install OpenCV-Python imutils scikit-image NumPy

您将使用OpenCV-Python获取图像输入并进行一些图像处理,使用Imutils来调整输入和输出图像的大小,并使用scikit-image对图像施加阈值。NumPy将帮助您处理数组。

等待安装完成,并等待IDE更新项目骨干内容。骨干内容更新完成后,您就可以开始编程了。完整的源代码可以在GitHub代码库中找到。

 

导入已安装的库

打开main.py文件,导入所安装的库。这将使您能够在必要时调用和使用它们的函数。

import cv2
import imutils
from skimage.filters import threshold_local
from transform import perspective_transform

忽略perspective_transform方面抛出的错误。您完成处理transform.py文件的工作后,错误会消失。

 

获取并调整输入的大小

为想要扫描的文档拍摄一张清晰的图像。确保文档的四个角及其内容都可见。将图像复制到存储程序文件的同一个文件夹中。

将输入图像路径传递给OpenCV。制作原始图像的副本,因为您在透视转换期间需要它。将原始图像的高度除以您想要调整到的高度。这将保持纵横比。最后,输出调整后的图像。

# Passing the image path
original_img = cv2.imread('sample.jpg')
copy = original_img.copy()

# The resized height in hundreds
ratio = original_img.shape[0] / 500.0
img_resize = imutils.resize(original_img, height=500)

# Displaying output
cv2.imshow('Resized image', img_resize)

# Waiting for the user to press any key
cv2.waitKey(0)

上述代码的输出如下:

现在您已经将原始图像的高度调整为500像素。

 

将调整后的图像转换为灰度图像

将调整后的RGB图像转换为灰度图像。大多数图像处理库只处理灰度图像,因为它们更容易处理。

gray_image = cv2.cvtColor(img_resize, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayed Image', gray_image)
cv2.waitKey(0)

注意原始图像和灰度图像之间的区别。

彩色桌变成了黑白桌。

 

运用边缘检测器

对灰度图像运用高斯模糊滤镜以去除噪声。然后调用OpenCV canny函数来检测图像中存在的边缘。

blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
edged_img = cv2.Canny(blurred_image, 75, 200)
cv2.imshow('Image edges', edged_img)
cv2.waitKey(0)

边缘在输出上是可见的。

您将处理的边缘是文档的边缘。

 

寻找最大的轮廓

检测边缘图像中的轮廓。按降序排序,只保留五个最大的轮廓。通过循环排序后的轮廓,近似获取最大的四边轮廓。

cnts, _ = cv2.findContours(edged_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]

for c in cnts:
  peri = cv2.arcLength(c, True)
  approx = cv2.approxPolyDP(c, 0.02 * peri, True)

  if len(approx) == 4:
      doc = approx
      break

有四个边的轮廓很可能含有文档。

 

圈出文档轮廓的四个角

圈出检测到的文档轮廓的几个角。这将帮助您确定您的程序是否能够检测图像中的文档。

p = []

for d in doc:
  tuple_point = tuple(d[0])
  cv2.circle(img_resize, tuple_point, 3, (0, 0, 255), 4)
  p.append(tuple_point)

cv2.imshow('Circled corner points', img_resize)
cv2.waitKey(0)

对调整后的RGB图像圈出几个角。

检测到文档之后,现在需要从图像中提取文档。

 

使用扭曲透视获得所需的图像

扭曲透视(warp perspective)是一种计算机视觉技术,用于转换图像以纠正失真。它将图像转换成不同的平面,让您可以从不同的角度查看图像。

warped_image = perspective_transform(copy, doc.reshape(4, 2) * ratio)
warped_image = cv2.cvtColor(warped_image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Warped Image", imutils.resize(warped_image, height=650))
cv2.waitKey(0)

为了获得扭曲后的图像,您需要创建一个简单的模块来执行透视转换。

 

转换模块

该模块将对文档角的点进行排序。它还会将文档图像转换成不同的平面,并将相机角度更改为俯拍。

打开之前创建的那个transform.py文件,导入OpenCV库和NumPy库。

import numpy as np
import cv2

这个模块将含有两个函数。创建一个对文档角点的坐标进行排序的函数。第一个坐标将是左上角的坐标,第二个将是右上角的坐标,第三个将是右下角的坐标,第四个将是左下角的坐标。

def order_points(pts):
 # initializing the list of coordinates to be ordered
 rect = np.zeros((4, 2), dtype = "float32")

 s = pts.sum(axis = 1)

 # top-left point will have the smallest sum
 rect[0] = pts[np.argmin(s)]

 # bottom-right point will have the largest sum
 rect[2] = pts[np.argmax(s)]

 '''computing the difference between the points, the
 top-right point will have the smallest difference,
 whereas the bottom-left will have the largest difference'''
 diff = np.diff(pts, axis = 1)
 rect[1] = pts[np.argmin(diff)]
 rect[3] = pts[np.argmax(diff)]

 # returns ordered coordinates
 return rect

创建将计算新图像的角坐标,并获得俯拍的第二个函数。然后,它将计算透视变换矩阵,并返回扭曲的图像。

def perspective_transform(image, pts):
 # unpack the ordered coordinates individually
 rect = order_points(pts)
 (tl, tr, br, bl) = rect

 '''compute the width of the new image, which will be the
 maximum distance between bottom-right and bottom-left
 x-coordinates or the top-right and top-left x-coordinates'''
 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))

 '''compute the height of the new image, which will be the
 maximum distance between the top-left and bottom-left y-coordinates'''
 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))

 '''construct the set of destination points to obtain an overhead shot'''
 dst = np.array([
    [0, 0],
    [maxWidth - 1, 0],
    [maxWidth - 1, maxHeight - 1],
    [0, maxHeight - 1]], dtype = "float32")

 # compute the perspective transform matrix
 transform_matrix = cv2.getPerspectiveTransform(rect, dst)

 # Apply the transform matrix
 warped = cv2.warpPerspective(image, transform_matrix, (maxWidth, maxHeight))

 # return the warped image
 return warped

现在您已创建了转换模块。perspective_transform导入方面的错误现在将消失。

注意,显示的图像有俯拍。

 

运用自适应阈值,保存扫描输出

在main.py文件中,对扭曲的图像运用高斯阈值。这将给扭曲的图像一个扫描后的外观。将扫描后的图像输出保存到含有程序文件的文件夹中。

T = threshold_local(warped_image, 11, offset=10, method="gaussian")
warped = (warped_image > T).astype("uint8") * 255
cv2.imwrite('./'+'scan'+'.png',warped)

以jpg格式保存扫描件可以保持文档质量。

 

显示输出

输出扫描后文档的图像:

cv2.imshow("Final Scanned image", imutils.resize(warped, height=650))
cv2.waitKey(0)
cv2.destroyAllWindows()

下图显示了程序的输出,即扫描后文档的俯拍。

关于Python构建一个文档扫描器的实现的文章就介绍至此,更多相关Python 文档扫描器内容请搜索编程宝库以前的文章,希望以后支持编程宝库

 python random库简单使用demo当我们需要生成随机数或者从一个序列中随机选择元素时,可以使用 Python 内置的 random 库。下面是一个带有注释的例子,演示了如 ...