Python如何实现OCR

2023-02-18  本文已影响0人  田陌允

一、离线方法
可以使用Python中的Tesseract OCR库。Tesseract是一个免费的OCR引擎,由谷歌开发,可在Windows、macOS和Linux等各种操作系统上运行。

pip install pytesseract
import pytesseract
from PIL import Image
image = Image.open('image.png')
text = pytesseract.image_to_string(image)
print(text)

实测效果很一般,至少中文是这样

二、在线方法
百度OCR API算是比较好用的,它支持多种图像格式和语言。以下是一个使用Python调用百度OCR API进行文字识别的大致步骤:

pip install baidu-aip

from aip import AipOcr
from PIL import Image
import io
APP_ID = 'your_app_id'
API_KEY = 'your_api_key'
SECRET_KEY = 'your_secret_key'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
image = Image.open('image.png')
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
image_data = img_byte_arr.getvalue()

result = client.basicGeneral(image_data)
if 'words_result' in result:
    for word in result['words_result']:
        print(word['words'])
else:
    print('OCR failed!')

PS:您需要将your_app_id、your_api_key和your_secret_key替换为您自己的API Key和Secret Key。并且,百度OCR API仅支持上传小于4MB的图像。

若你觉得图很一般,那就不要点赞了囧
上一篇 下一篇

猜你喜欢

热点阅读