利用Tesseract-ocr進(jìn)行圖片文字識(shí)別

文章作者:易明
個(gè)人博客:https://yiming1012.github.io
簡書主頁:http://m.itdecent.cn/u/6ebea55f5cec
郵箱地址:1129079384@qq.com

背景簡介

????最近有一個(gè)需求,識(shí)別隨車清單圖片,并提取關(guān)鍵信息。經(jīng)過調(diào)研選取了兩種方法嘗試:

1、Google維護(hù)的Tesseract-ocr
2、百度云OCR

Tesseract-ocr介紹

1、從https://github.com/UB-Mannheim/tesseract/wiki
下載對(duì)應(yīng)的版本。推薦4.0以上。

2、安裝過程中需要下載Additional language data。你可以全選,也可以只下載中文包。安裝的過程比較漫長……

3、測試Tesseract

  1. 查看版本:tesseract -v



    2.查看語言:tesseract --list-langs



    3.識(shí)別圖片:tesseract hua.png out

由上面看出,識(shí)別出來的都是啥啊。

4、通過Python識(shí)別圖片文字。

  1. Python代碼
# -*- coding: utf-8 -*-
from PIL import Image as myImage
import pytesseract
# 指定tesseract路徑
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
# 讀取圖片
img = myImage.open('hua.png')
# 識(shí)別圖片
text = pytesseract.image_to_string(img, lang='chi_sim')
print(text)
  1. 待識(shí)別的圖片


  2. 識(shí)別效果

    可以看出,tesseract-ocr的識(shí)別效果較差。不過,它的優(yōu)勢是可以通過jTessBoxEditor工具來修正錯(cuò)誤數(shù)據(jù)訓(xùn)練字庫,感興趣的同學(xué)可以嘗試,這里不再贅述。

百度云OCR

1、調(diào)用百度云文字識(shí)別的API,首先需要進(jìn)入百度智能云官網(wǎng)——產(chǎn)品服務(wù)——文字識(shí)別——應(yīng)用列表——?jiǎng)?chuàng)建應(yīng)用。創(chuàng)建成功之后,便可以獲的AppID、API KeySecret Key三個(gè)參數(shù)。


2、Python開發(fā)者可以參考Python-SDK指南,其中對(duì)Python如何調(diào)用接口以及具體參數(shù)配置做了詳細(xì)說明。其他語言開發(fā)者可以參考該網(wǎng)站其他SDK文檔。
3、通過pip安裝baidu-aip包: pip install baidu-aip
4、代碼展示:

# -*- coding: gbk -*-
from aip import AipOcr
import pandas as pd

# 配置百度參數(shù)
config = {
    'appId': 'yourappid',
    'apiKey': 'yourapiKey',
    'secretKey': 'yoursecretKey'
}
client = AipOcr(**config)

def get_file_content(file):
    with open(file, 'rb') as fp:
        return fp.read()

def img_to_str(image_path):
    image = get_file_content(image_path)
    """ 如果有可選參數(shù) """
    options = {}
    # 是否檢測圖像朝向,默認(rèn)不檢測
    options["detect_direction"] = "true"
    # 是否返回識(shí)別結(jié)構(gòu)中每一行的置信度
    options["probability"] = "true"
    # result = client.basicGeneral(image)
    result = client.basicAccurate(image, options)
    print(result.get("words_result"))
    df = pd.DataFrame(result.get("words_result"))
    return df

pictureContent = img_to_str('hua.png')
print(pictureContent)
print(list(pictureContent['words']))

5、效果展示



其中,圖片為向左旋轉(zhuǎn)90度后的,從上面看出,該接口能檢測圖片朝向,并能識(shí)別圖中文字,而且準(zhǔn)確率非常高。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容