搜索
首页后端开发Python教程如何用Python构建一个文档扫描器?

如何用Python构建一个文档扫描器?

Apr 26, 2023 pm 01:10 PM
python文档扫描器

​译者 | 布加迪

审校 | 孙淑娟

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

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

1、准备好环境

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

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

pip install OpenCV-Python imutils scikit-image NumPy

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

如何使用Python构建一个文档扫描器?

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

2、导入已安装的库

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

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

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

3、获取并调整输入的大小

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

如何使用Python构建一个文档扫描器?

将输入图像路径传递给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)

上述代码的输出如下:

如何使用Python构建一个文档扫描器?

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

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

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

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

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

如何使用Python构建一个文档扫描器?

IDE上显示灰色映像的程序输出

彩色桌变成了黑白桌。

5、运用边缘检测器

对灰度图像运用高斯模糊滤镜以去除噪声。然后调用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)

边缘在输出上是可见的。

如何使用Python构建一个文档扫描器?

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

6、寻找最大的轮廓

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

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

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

7、圈出文档轮廓的四个角

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

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图像圈出几个角。

如何使用Python构建一个文档扫描器?

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

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

扭曲透视(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)

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

9、转换模块

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

打开之前创建的那个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导入方面的错误现在将消失。

如何使用Python构建一个文档扫描器?

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

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

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

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

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

11、显示输出

输出扫描后文档的图像:

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

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

如何使用Python构建一个文档扫描器?

12、计算机视觉在如何进步?

创建文档扫描器涉及计算机视觉的一些核心领域,计算机视觉是一个广泛而复杂的领域。为了在计算机视觉方面取得进步,您应该从事有趣味又有挑战性的项目。

您还应该阅读如何将计算机视觉与当前前技术结合使用方面的更多信息。这让您能了解情况,并为所处理的项目提供新的想法。

原文链接:https://www.makeuseof.com/python-create-document-scanner/

以上是如何用Python构建一个文档扫描器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:51CTO.COM。如有侵权,请联系admin@php.cn删除
可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您应该检查脚本是否使用错误的Python版本执行?您应该检查脚本是否使用错误的Python版本执行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。