python数据采集11-图像识别与文字处理

版权声明:欢迎转载,注明出处就好!如果不喜欢请留言说明原因再踩哦,谢谢,这样我也可以知道原因,不断进步!! https://blog.csdn.net/jankin6/article/details/86523439

OCR库概述

在读取和处理图像、图像相关的机器学习以及创建图像等任务中,Python 一直都是非常出
色的语言。虽然有很多库可以进行图像处理,但在这里我们只重点介绍两个库:Pillow 和
Tesseract

Pillow

尽管 Pillow 算不上是图像处理功能最全的库,但是它拥有你需要使用的全部功能,除非你
要用 Python 重写一个 Photoshop 或进行更加复杂的研究。它也是一个文档健全且十分易用
的库。

Pillow 是从 Python 2.x 版本的 Python 图像库(Python Imaging Library,PIL)分出来的,支
持 Python 3.x 版本。和 PIL 一样,Pillow 也可以轻松地导入代码,并通过大量的过滤、修
饰甚至像素级的变换操作处理图片:


from PIL import Image, ImageFilter
kitten = Image.open("kitten.jpg")
blurryKitten = kitten.filter(ImageFilter.GaussianBlur)
blurryKitten.save("kitten_blurred.jpg")
blurryKitten.show()

Tesseract

Tesseract 是一个 OCR 库,目前由 Google 赞助(Google 也是一家以 OCR 和机器学习技术
闻名于世的公司)。Tesseract 是目前公认最优秀、最精确的开源 OCR 系统。

inux 用户可以通过 apt-get 安装:


$sudo apt-get tesseract-ocr

$ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/ \
install/master/install)"
$brew install tesseract

NumPy

虽然 NumPy 并非解决 OCR 问题时必须使用的库,但是如果你想训练 Tesseract 识别本章后
面提到的字符或字体,那么就会用到它。NumPy 是一个非常强大的库,具有大量线性代数
以及大规模科学计算的方法。因为 NumPy 可以用数学方法把图片表示成巨大的像素数组,
所以它可以流畅地配合 Tesseract 完成任务。

和其他 Python 库一样,NumPy 可以通过第三方包管理器(比如 pip)来安装

$pip install numpy

$tesseract text.tif textoutput | cat textoutput.txt

from PIL import Image
import subprocess
def cleanFile(filePath, newFilePath):
image = Image.open(filePath)
# 对图片进行阈值过滤,然后保存
image = image.point(lambda x: 0 if x<143 else 255)
image.save(newFilePath)
# 调用系统的tesseract命令对图片进行OCR识别
subprocess.call(["tesseract", newFilePath, "output"])
# 打开文件读取结果
outputFile = open("output.txt", 'r')
print(outputFile.read())
outputFile.close()
cleanFile("text_2.jpg", "text_2_clean.png")

猜你喜欢

转载自blog.csdn.net/jankin6/article/details/86523439
今日推荐