python使用百度aip文字識別
阿新 • • 發佈:2018-12-31
一、首先要有百度賬號
一般百度賬號都是通用的,如果沒有可以在百度AI開放平臺註冊一個賬號。
地址:http://ai.baidu.com
二、安裝sdk
pip install baidu-aip
備註:在pycharm裡也可以在setting----Project Interpreter—右邊綠色加號,輸入baidu,安裝baidu-aip
三、建立應用
登入百度雲控制檯,文字識別 --> 建立應用 --> 應用名稱等內容自己根據需要填寫
應用建立完成後,會生成一個應用,欄位代表的含義
AppID #賬號ID APIkey #針對介面訪問的授權方式 SecretKey #金鑰
四、文字識別程式碼
#!/usr/bin/env python #-*- coding:utf-8 -*- from aip import AipOcr # 文字識別 pip install baidu-aip import os # 定義變數 AppID = "15245350" #賬號ID APIkey = "6CVO9xxxxxxxxxxxx" #針對介面訪問的授權方式 SecretKey = "BkrxxxxxxxxxxxxB6W7AMuC" #金鑰 IMG_EXT = ['.png', '.jpg', '.jpeg', '.bmp'] #常見圖片格式字尾名 # 初始化操作 client = AipOcr(AppID, APIkey, SecretKey) # 1、呼叫介面獲取圖片裡面的文字內容 def cor_basic_general(file_path_name): print('圖片轉換地址為:{}'.format(file_path_name)) with open(file_path_name, 'rb') as f: content = f.read() api_result = client.basicGeneral(content) # 呼叫通用文字識別介面 # print(api_result) """ api_result的值:{ 'log_id': 3303489525243973687, 'words_result_num': 4, 'words_result': [{ 'words': '修仙路,踏歌行。身懷萬陣之祖,如何登上遺忘之巔?世界頂級僱傭兵王穿越了,來到了一片遺忘之地,這裡崇' }, { 'words': '尚力量,強者為尊。造槍造炮賣胸罩,打人打臉賣保險,彈琴唱歌修真路,殺人奪寶難拘束!這個世界太瘋狂' }, { 'words': '了,摩托車會飛,槍炮與法寶共存,不僅有飛來飛去的神仙姐姐,還有這身材惹火的職業御姐……這不是想象' }, { 'words': '是真實的,因為它就在我們“隔壁' }]}""" words_result = (i['words'] for i in api_result['words_result']) # 文字內容 result = '\n'.join(words_result) # 圖片的文字內容按照換行符拼接 return result # 2、判斷檔案型別,寫入檔案 def handdle_file(file_path_name): filename,ext = os.path.splitext(file_path_name) # 將檔名和拓展名分開 if ext in IMG_EXT: newname = filename + '.txt' # 儲存到txt檔案 result = cor_basic_general(file_path_name) # 呼叫上述方法 with open(newname, 'w',encoding='utf-8') as f: f.write(result) # 3、處理路徑下的所有圖片 def handdle_path(path): if os.path.isdir(path): for child_dir_or_file in os.listdir(path): child_path = os.path.join(path, child_dir_or_file) if os.path.isfile(child_path): handdle_file(child_path) else: handdle_path(child_path) if __name__ == '__main__': file_path = r'H:\python\ocr' # 圖片路徑 handdle_path(file_path)
五、擴充套件
人臉識別和文字識別類似,程式碼如下
#!/usr/bin/env python #-*- coding:utf-8 -*- from aip import AipFace """ 人臉識別的 APPID AK SK """ AppID = "15245350" #賬號ID APIkey = "6CVO9xxxxxxxxxxxx" #針對介面訪問的授權方式 SecretKey = "BkrxxxxxxxxxxxxB6W7AMuC" #金鑰 #初始化操作 client = AipFace(AppID, APIkey, SecretKey) """ 讀取圖片 """ def get_file_content(file_path_name): with open(file_path_name, 'rb') as fp: return fp.read() images = [ get_file_content('example0.jpg'), get_file_content('example1.jpg'), ] """ 呼叫人臉比對 """ result_json = client.match(images); print(result_json) result = result_json['result'][0]['score'] if result > 80: print("同一個人") else: print("不是同一個人")