调用百度AI识图实现通用物体和场景识别并重新命名图片,保存结果

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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值