Python OCR證件照文字識(shí)別

一.引言

文字識(shí)別,也稱為光學(xué)字符識(shí)別(Optical Character Recognition, OCR),是一種將不同形式的文檔(如掃描的紙質(zhì)文檔、PDF文件或數(shù)字相機(jī)拍攝的圖片)中的文字轉(zhuǎn)換成可編輯和可搜索的數(shù)據(jù)的技術(shù)。隨著技術(shù)的發(fā)展,文字識(shí)別技術(shù)已經(jīng)成為信息管理、自動(dòng)化辦公和智能系統(tǒng)的關(guān)鍵組成部分。

二.簡(jiǎn)介

為了易于集成和使用,我們將文字識(shí)別OCR封裝為DLL(動(dòng)態(tài)鏈接庫(kù))。這種封裝方式不僅保留了算法的性能優(yōu)勢(shì),還提供了跨平臺(tái)和跨語(yǔ)言的兼容性,目前支持編程語(yǔ)言如下:

  • C++
  • Python
  • 易語(yǔ)言

1.C++頭文件


#ifndef __SN_OCR__H__
#define __SN_OCR__H__

#include "windows.h"

//返回參數(shù)
typedef struct SN_STATU {

    int code;           //錯(cuò)誤碼,如果為 0 表示成功,否則表示錯(cuò)誤號(hào)
    char message[4096]; //錯(cuò)誤信息,如果為 "OK" 表示成功,否則返回錯(cuò)誤信息

}SN_STATU;

/*啟動(dòng)OCR文字識(shí)別服務(wù)
*
* 參數(shù):
*   [in]  szOnnxFilePath:   設(shè)置 onnx 模型文件路徑,如果設(shè)置為 NULL,默認(rèn)和 DLL文件同級(jí)目錄
*   [out] pResult:          返回錯(cuò)誤信息,參數(shù)pResult->code(錯(cuò)誤碼)如果為 0 表示成功,否則表示錯(cuò)誤號(hào);
*
* 返回值:成功返回0,失敗返回錯(cuò)誤號(hào),詳細(xì)錯(cuò)誤信息請(qǐng)參考 pResult
*
*/
int WINAPI apiSNInitOCRServer(char* szOnnxFilePath, SN_STATU* pStatu);

/*創(chuàng)建OCR文字識(shí)別句柄
*
* 參數(shù):
*   [in]  szKey:        卡密(購(gòu)買卡密:https://shop.4yuns.com/links/7C9F16B7)
*   [in]  pOnnxFilePath:設(shè)置 onnx 模型文件路徑,如果設(shè)置為 NULL,默認(rèn)和 DLL文件同級(jí)目錄
*   [out] pResult:      返回錯(cuò)誤信息,參數(shù)pResult->code(錯(cuò)誤碼)如果為 0 表示成功,否則表示錯(cuò)誤號(hào);
*
* 返回值:成功返回句柄,失敗返回NULL
*
*/
HANDLE WINAPI apiSNCreateOCRHandle(char* szKey, char* szOnnxFilePath, SN_STATU* pStatu);

/*獲取OCR文字識(shí)別卡密到期時(shí)間
*
* 參數(shù):
*   [in]  handle:       句柄(通過(guò)調(diào)用apiSNCreateOCRHandle得到)
*   [out] pResult:      返回錯(cuò)誤信息,參數(shù)pResult->code(錯(cuò)誤碼)如果為 0 表示成功,否則表示錯(cuò)誤號(hào);
*
* 返回值:返回卡密到期時(shí)間,失敗返回NULL,錯(cuò)誤信息請(qǐng)查看參數(shù) pResult->message
*
*/
char* WINAPI apiSNGetKeyExpiresTime(HANDLE handle, SN_STATU* pResult);

/*獲取OCR文字識(shí)別結(jié)果(以json字符串形式返回)
*
* 參數(shù):
*   [in]  handle:           句柄(通過(guò)調(diào)用apiSNCreateOCRHandle得到)
*   [in]  szImageFilePath:  圖片路徑
*   [out] pResult:          返回錯(cuò)誤信息,參數(shù)pResult->code(錯(cuò)誤碼)如果為 0 表示成功,否則表示錯(cuò)誤號(hào);
*
* 返回值:返回OCR文字識(shí)別結(jié)果(以json字符串形式返回),失敗返回NULL,錯(cuò)誤信息請(qǐng)查看參數(shù) pResult->message
*
*/
char* WINAPI apiSNGetOCRFromImage(HANDLE handle, char* szImageFilePath, SN_STATU* pStatu);

/*釋放OCR文字識(shí)別句柄(釋放內(nèi)存)
*
* 參數(shù):
*   [in] handle:        句柄(通過(guò)調(diào)用apiSNCreateOCRHandle得到)
*
* 返回值:返回 0 表示成功,其他值表示錯(cuò)誤號(hào);
*
*/
int WINAPI apiSNDestroyOCRHandle(HANDLE handle);

#endif

2.Python調(diào)用dll接口

from ctypes import cdll, c_char_p, Structure, byref
import ctypes

# 定義SN_STATU結(jié)構(gòu)體
class SN_STATU(Structure):
    _fields_ = [("code", ctypes.c_int),
               ("message", c_char_p * 4096)]

# 加載DLL
lib = cdll.LoadLibrary('D://SNOCR.dll')

# 設(shè)置函數(shù)參數(shù)類型
lib.apiSNInitOCRServer.argtypes = [c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNInitOCRServer.restype = ctypes.c_int

lib.apiSNCreateOCRHandle.argtypes = [c_char_p, c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNCreateOCRHandle.restype = ctypes.c_void_p

lib.apiSNGetKeyExpiresTime.argtypes = [ctypes.c_void_p, ctypes.POINTER(SN_STATU)]
lib.apiSNGetKeyExpiresTime.restype = c_char_p

lib.apiSNGetOCRFromImage.argtypes = [ctypes.c_void_p, c_char_p, ctypes.POINTER(SN_STATU)]
lib.apiSNGetOCRFromImage.restype = c_char_p

lib.apiSNDestroyOCRHandle.argtypes = [ctypes.c_void_p]
lib.apiSNDestroyOCRHandle.restype = ctypes.c_int

# 初始化變量
statu = SN_STATU()
key = b"SNKJe9xffLhdFY7r3TcffXq44ThDVcE3BQFQFfVA9VG4"
onnx_path = b"D://SNOCR.onnx"
image_path = b"D://7.jpg"

# 1. 啟動(dòng)OCR服務(wù)
ret = lib.apiSNInitOCRServer(onnx_path, byref(statu))
if ret < 0:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()

# 2. 創(chuàng)建OCR句柄
handle = lib.apiSNCreateOCRHandle(key, onnx_path, byref(statu))
if not handle:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()

# 3. 獲取卡密到期時(shí)間
expires_time = lib.apiSNGetKeyExpiresTime(handle, byref(statu))
if not expires_time:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()
print(f"Expires Time: {expires_time.decode('utf-8')}")

# 4. 識(shí)別OCR,返回Json字符串
ocr_result = lib.apiSNGetOCRFromImage(handle, image_path, byref(statu))
if not ocr_result:
    print(f"Error:{statu.message.decode('utf-8')}")
    exit()
try:
    print(f"OCR Result: {ocr_result.decode('utf-8')}")
except UnicodeDecodeError:
    print(f"OCR Result: {ocr_result.decode('GBK')}")

# 5. 釋放內(nèi)存
lib.apiSNDestroyOCRHandle(handle)

# 等待輸入,防止程序直接退出
input("Press Enter to exit...")

三.效果演示

1.圖片1

22.jpg

識(shí)別效果:

{
    "type": 0,
    "task_id":  1,
    "err_code": 0,
    "ocr_result":   {
        "single_result":    [{
                "left": 80.136589,
                "top":  56.710590,
                "right":    413.614105,
                "bottom":   89.287964,
                "str_utf8": "包頭市特種設(shè)備追溯平臺(tái)",
                "rate": "0.981197"
            }, {
                "left": 171.293091,
                "top":  99.701866,
                "right":    329.740753,
                "bottom":   120.792061,
                "str_utf8": "設(shè)備編碼: 000001)",
                "rate": "0.970116"
            }, {
                "left": 81.693756,
                "top":  274.142029,
                "right":    229.766312,
                "bottom":   295.966248,
                "str_utf8": "RFID 掃描區(qū)域",
                "rate": "0.992770"
            }, {
                "left": 50,
                "top":  318.229156,
                "right":    181.250000,
                "bottom":   339.062500,
                "str_utf8": "投訴電話: 12365",
                "rate": "0.984698"
            }, {
                "left": 259.311310,
                "top":  352.951111,
                "right":    466.734924,
                "bottom":   371.130615,
                "str_utf8": "包頭市質(zhì)量技術(shù)監(jiān)督局制",
                "rate": "0.961233"
            }],
        "width":    "500",
        "height":   "384"
    }
}

2.圖片2

06.jpg

識(shí)別效果:

{
    "type": 0,
    "task_id":  1,
    "err_code": 0,
    "ocr_result":   {
        "single_result":    [{
                "left": 451.128448,
                "top":  110.489426,
                "right":    1138.148070,
                "bottom":   199.850967,
                "str_utf8": "中華人民共和國(guó)",
                "rate": "0.998395"
            }, {
                "left": 398.003052,
                "top":  250.290588,
                "right":    1189.906010,
                "bottom":   370.648926,
                "str_utf8": "居民身份證",
                "rate": "0.999714"
            }, {
                "left": 333.586945,
                "top":  605.802917,
                "right":    1028.648680,
                "bottom":   654.308594,
                "str_utf8": "簽發(fā)機(jī)關(guān)上海市公安局徐匯分局",
                "rate": "0.998378"
            }, {
                "left": 334.754303,
                "top":  712.041199,
                "right":    539.191406,
                "bottom":   752.816345,
                "str_utf8": "有效期限",
                "rate": "0.999937"
            }, {
                "left": 551.186523,
                "top":  713.943665,
                "right":    1061.341670,
                "bottom":   754.974915,
                "str_utf8": "2005.10.08-202510.08",
                "rate": "0.985583"
            }],
        "width":    "1313",
        "height":   "858"
    }
}

四.常見(jiàn)問(wèn)題

1.是否支持多線程

支持

五.更新日志

  • 2024.12.15 OCR 文字識(shí)別支持C++/Python/易語(yǔ)言

六.云盤源碼下載

?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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