溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python OCR文字識(shí)別的方法有哪些

發(fā)布時(shí)間:2023-05-04 09:19:56 來(lái)源:億速云 閱讀:130 作者:iii 欄目:開(kāi)發(fā)技術(shù)

今天小編給大家分享一下python OCR文字識(shí)別的方法有哪些的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

    將圖片翻譯成文字一般被稱為光學(xué)文字識(shí)別(Optical Character Recognition,OCR)??梢詫?shí)現(xiàn)OCR 的底層庫(kù)并不多,目前很多庫(kù)都是使用共同的幾個(gè)底層OCR 庫(kù),或者是在上面進(jìn)行定制。

    方法一: 使用easyocr模塊

    easyocr是基于torch的深度學(xué)習(xí)模塊

    easyocr安裝后調(diào)用過(guò)程中出現(xiàn)opencv版本不兼容問(wèn)題,所以放棄此方案。

    方法二:通過(guò)pytesseract調(diào)用tesseract

    優(yōu)點(diǎn):部署快,輕量級(jí),離線可用,免費(fèi)

    缺點(diǎn):自帶的中文庫(kù)識(shí)別率較低,需要自己建數(shù)據(jù)進(jìn)行訓(xùn)練

    Tesseract 是一個(gè)OCR 庫(kù),目前由Google 贊助(Google 也是一家以O(shè)CR 和機(jī)器學(xué)習(xí)技術(shù)聞名于世的公司)。Tesseract 是目前公認(rèn)最優(yōu)秀、最精確的開(kāi)源OCR 系統(tǒng)。

      除了極高的精確度,Tesseract 也具有很高的靈活性。它可以通過(guò)訓(xùn)練識(shí)別出任何字體(只要這些字體的風(fēng)格保持不變就可以),也可以識(shí)別出任何Unicode 字符。

    Tesseract的安裝與使用

    python 識(shí)別圖片上的數(shù)字,使用pytesseract庫(kù)從圖像中提取文本,而識(shí)別引擎采用 tesseract-ocr

    pytesseract是python包裝器,它為可執(zhí)行文件提供了pythonic API。

    1、安裝必要的包:

    pip install pillow
    pip install pytesseract

    2、安裝tesseract-ocr的識(shí)別引擎

    最新版本下載地址: https://github.com/UB-Mannheim/tesseract/wiki

    python OCR文字識(shí)別的方法有哪些

    或者更多版本的tesseract下載地址:https://digi.bib.uni-mannheim.de/tesseract/ 

      安裝完后,需要將Tesseract添加到系統(tǒng)變量中。

      環(huán)境變量: 我的電腦 ->屬性 -> 高級(jí)系統(tǒng)設(shè)置 ->環(huán)境變量 ->系統(tǒng)變量 ,在 path 中添加 安裝路徑。

    python OCR文字識(shí)別的方法有哪些

    并將訓(xùn)練好的模型文件 chi_sim.traineddata 放入該目錄中,這樣安裝就完成了。

    在命令行 WIN+R 輸入cmd :輸入 tesseract -v ,出現(xiàn)版本信息,則配置成功。

    python OCR文字識(shí)別的方法有哪些

    tesseract-ocr默認(rèn)不支持中文識(shí)別。支持中文識(shí)別.png

    python OCR文字識(shí)別的方法有哪些

    3、解決pytesseract 找不到路徑的問(wèn)題。

    在自己安裝的pytesseract包中,找到pytesseract.py文件

    python OCR文字識(shí)別的方法有哪些

    打開(kāi)pytesseract.py文件,修改 tesseract_cmd 的值:tesseract.exe 的安裝路徑 。

    為了避免其他的錯(cuò)誤,使用雙反斜杠,或者斜杠

    python OCR文字識(shí)別的方法有哪些

    4、簡(jiǎn)單使用

    import pytesseract
    from PIL import Image
    if __name__ == '__main__':
        text = pytesseract.image_to_string(Image.open("D:\\test.png"),lang="eng")  
        # 如果你想試試Tesseract識(shí)別中文,只需要將代碼中的eng改為chi_sim即可
        print(text)

    測(cè)試圖片:

    python OCR文字識(shí)別的方法有哪些

    輸出結(jié)果:

    python OCR文字識(shí)別的方法有哪些

    用Tesseract可以識(shí)別格式規(guī)范的文字,主要具有以下特點(diǎn):

    • 使用一個(gè)標(biāo)準(zhǔn)字體(不包含手寫(xiě)體、草書(shū),或者十分“花哨的”字體)

    • 雖然被復(fù)印或拍照,字體還是很清晰,沒(méi)有多余的痕跡或污點(diǎn)

    • 排列整齊,沒(méi)有歪歪斜斜的字

    • 沒(méi)有超出圖片范圍,也沒(méi)有殘缺不全,或緊緊貼在圖片的邊緣

      下面將給出幾個(gè)tesseract識(shí)別圖片中文字的例子。

      首先是E://figures/other/poems.jpg, 輸入命令 tesseract E://figures/other/poems.jpg E://figures/other/poems.txt, 則會(huì)將poems.jpg中的識(shí)別文字寫(xiě)入到poems.txt中,如下圖:

    python OCR文字識(shí)別的方法有哪些

    python OCR文字識(shí)別的方法有哪些

    python OCR文字識(shí)別的方法有哪些

    接著是稍微有點(diǎn)傾斜的文字圖片th.jpg,識(shí)別情況如下:

    python OCR文字識(shí)別的方法有哪些

    python OCR文字識(shí)別的方法有哪些

    可以看到識(shí)別的情況不如剛才規(guī)范字體的好,但是也能識(shí)別圖片中的大部分字母。

    最后是識(shí)別簡(jiǎn)體中文,需要事先安裝簡(jiǎn)體中文語(yǔ)言包,再講chi_sim.traineddata放在C:\Program Files (x86)\Tesseract-OCR\tessdata目錄下。我們以圖片timg.jpg為例:

    python OCR文字識(shí)別的方法有哪些

    輸入命令:

    tesseract E://figures/other/timg.jpg E://figures/other/timg.txt -l chi_sim

    識(shí)別結(jié)果如下:

    python OCR文字識(shí)別的方法有哪些

    只識(shí)別錯(cuò)了一個(gè)字,識(shí)別率還是不錯(cuò)的。

    最后加一句,Tesseract對(duì)于彩色圖片的識(shí)別效果沒(méi)有黑白圖片的效果好。

    pytesseract

    pytesseract是Tesseract關(guān)于Python的接口,可以使用pip install pytesseract安裝。安裝完后,就可以使用Python調(diào)用Tesseract了,不過(guò),你還需要一個(gè)Python的圖片處理模塊,可以安裝pillow.

      輸入以下代碼,可以實(shí)現(xiàn)同上述Tesseract命令一樣的效果:

    import pytesseract
    from PIL import Image
    pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)/Tesseract-OCR/tesseract.exe'
    text = pytesseract.image_to_string(Image.open('E://figures/other/poems.jpg'))
    print(text)

    運(yùn)行結(jié)果如下:

    python OCR文字識(shí)別的方法有哪些

    cnocr 第二種 Python 開(kāi)源識(shí)別工具的效果

    兩個(gè)工具的使用方法和對(duì)比效果。

    安裝 cnocr:

    pip install cnocr

    看到 Successfully installed xxx 則說(shuō)明安裝成功。

    如果你只想對(duì)圖片中的中文進(jìn)行識(shí)別,那么 cnocr 是一個(gè)不錯(cuò)的選擇,你只需要安裝 cnocr 包即可。

    但如果你想試試其他語(yǔ)言的OCR識(shí)別,Tesseract 是更好的選擇。

    cnocr 識(shí)別圖片的中文

    cnocr 主要針對(duì)的是排版簡(jiǎn)單的印刷體文字圖片,如截圖圖片,掃描件等。目前內(nèi)置的文字檢測(cè)和分行模塊無(wú)法處理復(fù)雜的文字排版定位。

    盡管它分別提供了單行識(shí)別函數(shù)和多行識(shí)別函數(shù),但在本人實(shí)測(cè)下,單行識(shí)別函數(shù)的效果非常糟糕,或者說(shuō)要求的條件十分苛刻,基本上連截圖的文字都識(shí)別不出來(lái)。

    不過(guò)多行識(shí)別函數(shù)還不錯(cuò),使用該函數(shù)識(shí)別的代碼如下:

    from cnocr import CnOcr
    ocr = CnOcr()
    res = ocr.ocr('test.png')
    print("Predicted Chars:", res)

    用于識(shí)別這個(gè)圖片里的文字:

    python OCR文字識(shí)別的方法有哪些

    效果如下:

    python OCR文字識(shí)別的方法有哪些

    如果不是很吹毛求疵,這樣的效果已經(jīng)很不錯(cuò)了。

    方法三:調(diào)用百度API

    優(yōu)點(diǎn):使用方便,功能強(qiáng)大

    缺點(diǎn):大量使用需要收費(fèi)

    我自己采用的是調(diào)用百度API的方式,下面是我的步驟:

    注冊(cè)百度賬號(hào),創(chuàng)建OCR應(yīng)用可以參考其他教程。

    購(gòu)買后使用python調(diào)用方法

    方式一: 通過(guò)urllib直接調(diào)用,替換自己的api_key和secret_key即可

    # coding=utf-8
    import sys
    import json
    import base64
    # 保證兼容python2以及python3
    IS_PY3 = sys.version_info.major == 3
    if IS_PY3:
        from urllib.request import urlopen
        from urllib.request import Request
        from urllib.error import URLError
        from urllib.parse import urlencode
        from urllib.parse import quote_plus
    else:
        import urllib2
        from urllib import quote_plus
        from urllib2 import urlopen
        from urllib2 import Request
        from urllib2 import URLError
        from urllib import urlencode
    # 防止https證書(shū)校驗(yàn)不正確
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context
    API_KEY = 'YsZKG1wha34PlDOPYaIrIIKO'
    SECRET_KEY = 'HPRZtdOHrdnnETVsZM2Nx7vbDkMfxrkD'
    OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    """  TOKEN start """
    TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
    """
        獲取token
    """
    def fetch_token():
        params = {'grant_type': 'client_credentials',
                  'client_id': API_KEY,
                  'client_secret': SECRET_KEY}
        post_data = urlencode(params)
        if (IS_PY3):
            post_data = post_data.encode('utf-8')
        req = Request(TOKEN_URL, post_data)
        try:
            f = urlopen(req, timeout=5)
            result_str = f.read()
        except URLError as err:
            print(err)
        if (IS_PY3):
            result_str = result_str.decode()
        result = json.loads(result_str)
        if ('access_token' in result.keys() and 'scope' in result.keys()):
            if not 'brain_all_scope' in result['scope'].split(' '):
                print ('please ensure has check the  ability')
                exit()
            return result['access_token']
        else:
            print ('please overwrite the correct API_KEY and SECRET_KEY')
            exit()
    """
        讀取文件
    """
    def read_file(image_path):
        f = None
        try:
            f = open(image_path, 'rb')
            return f.read()
        except:
            print('read image file fail')
            return None
        finally:
            if f:
                f.close()
    """
        調(diào)用遠(yuǎn)程服務(wù)
    """
    def request(url, data):
        req = Request(url, data.encode('utf-8'))
        has_error = False
        try:
            f = urlopen(req)
            result_str = f.read()
            if (IS_PY3):
                result_str = result_str.decode()
            return result_str
        except  URLError as err:
            print(err)
    if __name__ == '__main__':
        # 獲取access token
        token = fetch_token()
        # 拼接通用文字識(shí)別高精度url
        image_url = OCR_URL + "?access_token=" + token
        text = ""
        # 讀取測(cè)試圖片
        file_content = read_file('test.jpg')
        # 調(diào)用文字識(shí)別服務(wù)
        result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
        # 解析返回結(jié)果
        result_json = json.loads(result)
        print(result_json)
        for words_result in result_json["words_result"]:
            text = text + words_result["words"]
        # 打印文字
        print(text)

    方式二:通過(guò)HTTP-SDK模塊進(jìn)行調(diào)用

    from aip import AipOcr
    APP_ID = '25**9878'
    API_KEY = 'VGT8y***EBf2O8xNRxyHrPNr'
    SECRET_KEY = 'ckDyzG*****N3t0MTgvyYaKUnSl6fSw'
    client = AipOcr(APP_ID,API_KEY,SECRET_KEY)
    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()
    image = get_file_content('test.jpg')
    res = client.basicGeneral(image)
    print(res)
    #res = client.basicAccurate(image)
    #print(res)

    直接識(shí)別屏幕指定區(qū)域上的文字

    from aip import AipOcr
    APP_ID = '25**9878'
    API_KEY = 'VGT8y***EBf2O8xNRxyHrPNr'
    SECRET_KEY = 'ckDyzG*****N3t0MTgvyYaKUnSl6fSw'
    client = AipOcr(APP_ID,API_KEY,SECRET_KEY)
    from io import BytesIO
    from PIL import ImageGrab
    out_buffer = BytesIO()
    img = ImageGrab.grab((100,200,300,400))
    img.save(out_buffer,format='PNG')
    res = client.basicGeneral(out_buffer.getvalue())
    print(res)

    以上就是“python OCR文字識(shí)別的方法有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI