# # encoding:utf-8
import requests
import base64
import os
#
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=自己输入&client_secret=自己输入'
response = requests.get(host)
if response:
print(response.json())
'''
通用物体和场景识别
'''
def Identification(img):
# 识别物体请求头
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
# 二进制方式打开图片文件
f = open(img, 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = '自己输入'
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()
# 把读出的文字内容统一保存在一个txt文档里
f = open(r'../api/plateread.txt', 'w')
# 保存了待识别图片的路径
PlatePath = r'图片文件夹路径'
# 按顺序识别出图片,并把图片文件名改成“识别出的文字.jpg”的格式
for Dir in os.listdir(PlatePath):
img = os.path.join(PlatePath, Dir)
message = Identification(img)
# print( message['result'][0])
score = message['result'][0]['score']
root = message['result'][0]['root']
keyword = message['result'][0]['keyword']
name = keyword + '_' + root + "_" + str(score)
a = '%s识别结果为---------->%s_%s_相似度为%s' % (Dir, keyword, root, format(score, '.2%'))
print(a)
try:
f.write(a + '\n')
except Exception:
pass
dstDir = os.path.join(PlatePath, name) + '.jpg'
# print(dstDir)
try:
os.rename(img, dstDir)
except Exception:
pass
f.close()