Python 基于百度API的图像识别程序

使用百度API,ocr识别图片中的文字,参考网页https://ai.baidu.com/ai-doc/OCR/dk3iqnq51

 

代码如下:

melesOcr.py:

#  coding=utf-8
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow,QFileDialog
from w5 import Ui_MainWindow
import os
from ocrDemo import *
# 导入模块
#美獾小图片识别程序Ocr,调用百度API


class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
      
        self.setupUi(self)
        self.pushButton.clicked.connect(self.but1)
        self.pushButton_2.clicked.connect(self.closew)
        
        

        
    def but1(self):      
        try:  

            allt='识别后内容'
            open = QFileDialog()
            self.path=open.getOpenFileName(self,"选取文件",  
                                    ".", # 起始路径
                                    "图像文件(*.jpg *.png)")
            print(self.path)
            
            self.textBrowser.setText(self.path[0])
            # 获取access token
            token = fetch_token()
        
            # 拼接通用文字识别高精度url
            image_url = OCR_URL + "?access_token=" + token
        
            text = ""
        
            # 读取书籍页面图片
            #file_content = read_file('./text.jpg')
            file_content = read_file(self.path[0])
        
            # 调用文字识别服务
            result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
        
            # 解析返回结果
            result_json = json.loads(result)
            for words_result in result_json["words_result"]:
                text = text + words_result["words"]
        
            # 打印文字
            print(text)            
            self.plainTextEdit.setPlainText(text)
        except Exception as e:
            print(e)
    def closew(self):  
        try:                          # 编辑数据调用的方法
            self.close()
            sys.exit(app.exec())
        except Exception as e:
            print(e)
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())

==============================================================

ocrDemo.py:

# coding=utf-8
# 使用百度API,ocr识别图片中的文字,参考网页https://ai.baidu.com/ai-doc/OCR/dk3iqnq51
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证书校验不正确
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

API_KEY = '自己去申请'

SECRET_KEY = '自己的APIKey'


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()


"""
    调用远程服务
"""
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()

    # 拼接通用文字识别高精度url
    image_url = OCR_URL + "?access_token=" + token

    text = ""

    # 读取书籍页面图片
    #file_content = read_file('./text.jpg')
    file_content = read_file('./c68.jpg')

    # 调用文字识别服务
    result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))

    # 解析返回结果
    result_json = json.loads(result)
    for words_result in result_json["words_result"]:
        text = text + words_result["words"]

    # 打印文字
    print(text)

==============================================================

运行效果如图:

 

 

========================================================

软件限制说明:必须联网,只支持WIN10,WIN7无法使用。免费接口每天有调用次数限制。看窗口日志就能知道到上限了。软件下载链接:https://download.csdn.net/download/rishengcsdn/18972021

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值