一、離線方法
可以使用Python中的Tesseract OCR庫。Tesseract是一個免費的OCR引擎,由谷歌開發(fā),可在Windows、macOS和Linux等各種操作系統(tǒng)上運行。
- 安裝Tesseract OCR庫??梢允褂靡韵旅钤诮K端中安裝:
pip install pytesseract
- 導(dǎo)入必要的庫。在Python代碼中,您需要導(dǎo)入以下庫:
import pytesseract
from PIL import Image
- 加載圖片。使用以下代碼加載需要識別的圖像:
image = Image.open('image.png')
- 執(zhí)行OCR。使用以下代碼執(zhí)行OCR:
text = pytesseract.image_to_string(image)
print(text)
實測效果很一般,至少中文是這樣
二、在線方法
百度OCR API算是比較好用的,它支持多種圖像格式和語言。以下是一個使用Python調(diào)用百度OCR API進行文字識別的大致步驟:
創(chuàng)建百度OCR API應(yīng)用程序,并獲取API Key和Secret Key。
安裝百度AI開放平臺Python SDK??梢允褂靡韵旅钤诮K端中安裝:
pip install baidu-aip
- 導(dǎo)入必要的庫。在Python代碼中,您需要導(dǎo)入以下庫:
from aip import AipOcr
from PIL import Image
import io
- 初始化AipOcr對象。在Python代碼中,您需要使用您的API Key和Secret Key初始化AipOcr對象:
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')
- 執(zhí)行OCR。使用以下代碼將圖像上傳到百度OCR API進行處理,并獲取識別結(jié)果:
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的圖像。

若你覺得圖很一般,那就不要點贊了囧