python3使用Pillow、tesseract-ocr与pytesseract模块的图片识别的方法

  

下面是详细讲解“python3使用Pillow、tesseract-ocr与pytesseract模块的图片识别的方法”的完整攻略。

一、Pillow模块

Pillow是Python Imaging Library(PIL)的分支,提供了更加友好的API和更好的兼容性。

在使用前,需要先安装Pillow模块:

pip3 install Pillow

1. 读取图片

使用Pillow模块读取图片十分方便,可以使用Image模块中的打开图片方法:

from PIL import Image

img = Image.open('image.png')

2. 剪切图片

剪切图片可以使用Image模块中的crop方法:

# 从左上角剪切一个100*100的图片
box = (0,0,100,100)
img_crop = img.crop(box)

3. 图片缩放

图片缩放可以使用Image模块中的resize方法:

# 将图片缩放为原来的一半
img_resize = img.resize((img.width//2, img.height//2))

4. 图片灰度化

图片灰度化可以使用Image模块中的convert方法实现:

img_gray = img.convert('L')

二、tesseract-ocr模块

tesseract-ocr是一个开源的OCR(Optical Character Recognition)引擎,可以识别各种语言的字符。

在使用前,需要先安装tesseract-ocr模块:

sudo apt-get install tesseract-ocr

1. 识别图片

使用tesseract-ocr识别图片可以使用subprocess模块中的检查输出方法:

import subprocess

# 推荐使用具体的语言代码,比如中文语言代码是chi_sim
output = subprocess.check_output(['tesseract', 'image.png', 'out', '-l', 'eng'])

# 通过读取out.txt文件获取识别结果
with open('out.txt', 'r', encoding='utf-8') as f:
    result = f.read().strip()

三、pytesseract模块

pytesseract是对tesseract-ocr进行封装的Python模块,提供了更加友好的API。

在使用前,需要先安装pytesseract模块和tesseract-ocr模块:

sudo apt-get install tesseract-ocr
pip3 install pytesseract

1. 识别图片

使用pytesseract识别图片也十分简单:

import pytesseract

# 推荐使用具体的语言代码,比如中文语言代码是chi_sim
result = pytesseract.image_to_string(Image.open('image.png'), lang='eng')

2. 声明tesseract-ocr路径

有时候tesseract-ocr被安装在非默认路径时,需要指定tesseract-ocr路径:

import pytesseract

# 声明tesseract-ocr路径
pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract'

# 推荐使用具体的语言代码,比如中文语言代码是chi_sim
result = pytesseract.image_to_string(Image.open('image.png'), lang='eng')

以上是“python3使用Pillow、tesseract-ocr与pytesseract模块的图片识别的方法”的攻略。

示例1:

假设有一张名为'captcha.png'的图片,需要识别图片中的验证码,代码如下:

# 导入相关模块
from PIL import Image
import pytesseract

# 打开图片
img = Image.open('captcha.png')

# 识别图片中的文字
captcha_code = pytesseract.image_to_string(img, lang='eng')

# 输出验证码
print(captcha_code)

示例2:

假设有一张名为'passport.png'的图片,图片中有一个姓名,需要识别这个姓名,代码如下:

# 导入相关模块
from PIL import Image
import pytesseract

# 打开图片
img = Image.open('passport.png')

# 将图片转为灰度图
img = img.convert('L')

# 剪切图片,获取姓名
name_box = (50, 50, 200, 100)
name_img = img.crop(name_box)

# 识别图片中的文字
name = pytesseract.image_to_string(name_img, lang='eng')

# 输出姓名
print(name)

以上就是本次攻略的详细内容,希望能对你有所帮助。

相关文章