关键词

Python3实现获取图片文字里中文的方法分析

Python3实现获取图片文字里中文的方法分析

当我们需要处理包含中文的图片文字时,可以使用Python3中的OCR技术,将其转换为计算机可读的文本文件,从而方便后续处理。本文将通过以下步骤详细讲解如何使用Python3实现获取图片文字里中文的方法。

步骤一:安装OCR引擎

使用Python3实现OCR需要安装OCR引擎,常用的包括Tesseract和OCRopus等。本文以Python3 OCR库中的Tesseract为例进行讲解,安装方法如下:

pip install pytesseract

步骤二:安装Tesseract OCR引擎

安装Python OCR库后,需要安装Tesseract OCR引擎,可从以下网址下载:

https://github.com/tesseract-ocr/tesseract

安装完成后,将其加入环境变量中,或使用语句进行配置:

import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'

步骤三:加载图片文件

加载包含中文文字的图片文件,常用的格式包括jpg、png等。使用Python3中的Pillow库进行图片文件读取,代码示例如下:

from PIL import Image

img = Image.open('test.jpg')

步骤四:调用OCR引擎识别图片文字

使用Tesseract OCR引擎识别图片文件中的中文文字:

text = pytesseract.image_to_string(img, lang='chi_sim')

其中lang为图片文字的语言设置,chi_sim表示简体中文。

步骤五:输出识别结果

将识别出的中文文字保存到文本文件中或输出至控制台:

with open('result.txt', mode='w') as file:
    file.write(text)
    print('ocr result:', text)

示例一:图片中的文字

假设我们有一张包含中文文字的图片文件test.jpg,使用上述步骤可以获取到该文件中的中文文字内容,代码示例如下:

from PIL import Image
import pytesseract

img = Image.open('test.jpg')
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'
text = pytesseract.image_to_string(img, lang='chi_sim')
with open('result.txt', mode='w') as file:
    file.write(text)
    print('ocr result:', text)

示例二:批量处理图片中的文字

对于批量的图片文件,可以使用os库进行遍历,将每一张图片文件中的中文文字提取出来,代码示例如下:

from PIL import Image
import pytesseract
import os

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'
img_dir = './images'
result_dir = './results'
if not os.path.exists(result_dir):
    os.makedirs(result_dir)
for i, img_file in enumerate(os.listdir(img_dir)):
    img_path = os.path.join(img_dir, img_file)
    img = Image.open(img_path)
    text = pytesseract.image_to_string(img, lang='chi_sim')
    with open(os.path.join(result_dir, f'result_{i}.txt'), mode='w') as f:
        f.write(text)
        print(f'saving result_{i}.txt done')

通过上述代码,可以将images文件夹下所有图片文件中的中文文字提取出来,并保存到结果文件夹results中,每个文件对应一张原始图片文件,文件名以result_开头,后添加数字序号。

本文链接:http://task.lmcjl.com/news/14631.html

展开阅读全文