最近研究了一下用python识别图像上的文字,发现其简直是太方便了,只需安装好Tesseract-OCR环境,然后直接调用就能把文字识别出来。
Tesseract,一款由HP实验室开发由Google维护的开源OCR(Optical Character Recognition , 光学字符识别)引擎,与Microsoft Office Document Imaging(MODI)相比,我们可以不断的训练的库,使图像转换文本的能力不断增强;如果团队深度需要,还可以以它为模板,开发出符合自身需求的OCR引擎。
具体安装Tesseract-OCR环境参考博客:https://blog.csdn.net/qq_43317529/article/details/83340739
还有在写程序时候要记得导入对应的几个包,识别图像上的文字就一行代码:
text = pytesseract.image_to_string(Image.open('test.jpg'),lang='chi_sim')
没错,就这么简洁明了。
然后翻译部分是调用了有道词典的翻译,当然百度翻译、搜狗翻译等都可以。
from PIL import Image
import pytesseract
import json
import requests
text = pytesseract.image_to_string(Image.open('test.jpg'),lang='chi_sim')
print (text)
# 翻译函数,word 需要翻译的内容
def translate(word):
# 有道词典 api
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
# 传输的参数,其中 i 为需要翻译的内容
key = {
'type': "AUTO",
'i': word,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"ue": "UTF-8",
"action": "FY_BY_CLICKBUTTON",
"typoResult": "true"
}
# key 这个字典为发送给有道词典服务器的内容
response = requests.post(url, data=key)
# 判断服务器是否相应成功
if response.status_code == 200:
# 然后相应的结果
return response.text
else:
print("有道词典调用失败")
# 失败就返回空
return None
def get_reuslt(repsonse):
# 通过 json.loads 把返回的结果加载成 json 格式
result = json.loads(repsonse)
print ("翻译:%s" % result['translateResult'][0][0]['tgt'])
def main():
list_trans = translate(text)
get_reuslt(list_trans)
if __name__ == '__main__':
main()
识别的照片:
识别结果: