【Python学习】借助百度智能云实现图片文字识别

我觉得这是个非常实用的功能,特别是刚刚结束的这学期,线上课,很多实验要求电子版,手敲字又很累,手机识别图片中的文字的又不是特别准。
所以,这个的用途就显现出来啦,可以把图片中的文字识别出来,非常棒,准确性极高。

获得API KEY和SECRET KEY

第一步

在搜索引擎里搜索百度智能云,第一个就是

image

第二步

首页内选择产品中的人工智能,点击通用场景文字识别

image

然后进入下面这个界面

image

技术文档

在技术文档里面,会给参考的代码,使用这些代码就可以轻松实现文字识别功能

image

里面也包括对参数的一些说明

image

立即使用

点击免费尝鲜,可以免费领取

image

勾选全部

image

领取成功之后我们就可以创建应用啦

第三步 创建应用

创建应用,前面的两个是我之前创建过的

image

应用归属选择个人即可
image

创建成功后返回应用列表

image

刚刚创建成功的,代码中用到的就是API key和Secret key

image

代码部分

代码使用的就是技术文档中提供的代码示例,只要把API_KEY和SECRET_KEY替换成我们刚刚创建应用中的就可以

点击查看代码
import sys
import json
import base64
import requests
import ssl
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

API_KEY = '你的API_KEY,就是刚刚创建应用中的那个'# 要以字符串的形式哦!!!!
SECRET_KEY = '你的SECRET_KEY,就是刚刚创建应用中的那个'# 要以字符串的形式哦!!!!


def fetch_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + API_KEY + '&client_secret=' + SECRET_KEY
    response = requests.get(host)
    if response:
        result = response.json()
        return result['access_token']


def read_file(image_path):
    f = open(image_path, 'rb')
    return f.read()
    f.close()


def ocr(token, picture_file):
    img = base64.b64encode(picture_file)
    params = {"image": img}
    access_token = token
    request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.json()


if __name__ == '__main__':
    token = fetch_token()
    picture_file = read_file('./2.jpg')
    result_json = ocr(token, picture_file)
    text = ""
    for words_result in result_json["words_result"]:
        text = text + words_result["words"]
    print(text)

运行效果

我们来看一下效果吧

这个是书的图片,《无人生还》

image

这个是文字识别的结果

image

参考资料

云计算导论(第2版)

ok,以上就是全部内容啦,希望对你有帮助

posted @ 2022-07-17 22:02  寥若辰星  阅读(719)  评论(4编辑  收藏  举报