【Python】调用百度云API文字识别服务 OCR
生活随笔
收集整理的這篇文章主要介紹了
【Python】调用百度云API文字识别服务 OCR
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# encoding:utf-8
# !/usr/local/bin/python3# 百度云:文字識(shí)別服務(wù)
# 應(yīng)用名稱:文字識(shí)別練習(xí)項(xiàng)目import urllib3
from urllib.parse import urlencode
import urllib
import urllib.request
import sys
import ssl
import base64
import json'''
# 調(diào)用API前必須獲取Access Token
# client_id 為官網(wǎng)獲取的AK, client_secret 為官網(wǎng)獲取的SK
# access_token: 要獲取的Access Token;
# expires_in: Access Token的有效期(秒為單位,一般為1個(gè)月);
'''
APPId = 17165172
ApiKey = 'uck9A45flml7ITBQ8VaLUojf'
SecretKey = 'p19Nl1Rz1DGGMKepK3lNDWk8TogqankG'
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ApiKey+'&client_secret='+SecretKey
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
if (content):#print(content) # 打印獲取到的信息# 通過(guò)decode將bytes字節(jié)串轉(zhuǎn)換為字符串strcontent = content.decode('utf-8')contentDict = json.loads(content) # 借助json函數(shù)將str轉(zhuǎn)換為dictrefresh_token = contentDict["refresh_token"] # 直接讀取dict字典內(nèi)需要的數(shù)據(jù)expires_in = contentDict["expires_in"]session_key = contentDict["session_key"]access_token = contentDict["access_token"]scope = contentDict["scope"]session_secret = contentDict["session_secret"]#print(access_token)'''
手寫文字識(shí)別
# 所有圖片均需要base64編碼、去掉編碼頭后再進(jìn)行urlencode。
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting" #手寫文字識(shí)別接口
imagePath = '/Users/zhaojichao/Desktop/ocrtest.jpg' # 測(cè)試100001
f = open(imagePath, 'rb')
# img為bytes類型
img = base64.b64encode(f.read())
# img為str類型
img = img.decode('utf-8')
params = {"image": img}#"recognize_granularity": "BASE64",#"words_type": "16_219"}
# 對(duì)base64數(shù)據(jù)進(jìn)行urlencode處理編碼之后格式為str
params = urllib.parse.urlencode(params)
# str轉(zhuǎn)為可以提交的bytes
params = params.encode('utf-8')
access_token = access_token
request_url = request_url + "?access_token=" + access_token
request = urllib.request.Request(url=request_url, data=params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
response = urllib.request.urlopen(request)
content = response.read()
if content:# 返回?cái)?shù)據(jù)為bytes,需要轉(zhuǎn)換為strcontent = content.decode('utf-8')print(content)
總結(jié)
以上是生活随笔為你收集整理的【Python】调用百度云API文字识别服务 OCR的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Python】调用百度云API人脸检测
- 下一篇: 【Python】调用百度云API驾驶行为