一.平台接入
此步骤比较简单,不多阐述。可参照上篇文档:
https://ai.baidu.com/forum/topic/show/943028
二.分析接口文档
1.打开http://ai.baidu.com/docs#/ImageClassify-API/fe686c3a,查看接口说明
(1)接口描述
该请求用于检测一张车辆图片的具体车型。即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。
注:当前只支持单主体识别,若图片中有多个车辆,则识别目标最大的车辆。
(2)请求说明
需要用到的信息有:
请求URL: https://aip.baidubce.com/rest/2.0/image-classify/v1/car
Header格式:Content-Type:application/x-www-form-urlencoded
URL参数:
image, 图像数据,base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 。注意:图片需要base64编码、去掉编码头后再进行urlencode。
top_num:返回准确率最高的几个识别结果,返回结果top n,默认5。
baike_num:返回百科信息的结果数,默认不返回
2.获取accesstoken
#client_id 为官网获取的AK, client_secret 为官网获取的SK
client_id =【百度云应用的AK】
client_secret =【百度云应用的SK】
#获取token
def get_token():
host = ‘https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=’ + client_id + ‘&client_secret=’ + client_secret
request = urllib.request.Request(host)
request.add_header(‘Content-Type’, ‘application/json; charset=UTF-8’)
response = urllib.request.urlopen(request)
token_content = response.read()
if token_content:
token_info = json.loads(token_content.decode(“utf-8”))
token_key = token_info[‘access_token’]
return token_key
3.准备一张用于识别的图片,存储在本地
三.识别结果
四.源码共享
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import urllib
import urllib.parse
import urllib.request
import base64
import json
#client_id 为官网获取的AK, client_secret 为官网获取的SK
client_id = '****************'
client_secret = '************************'
#获取token
def get_token():
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
token_content = response.read()
if token_content:
token_info = json.loads(token_content.decode("utf-8"))
token_key = token_info['access_token']
return token_key
# 读取图片
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
#获取汽车型号信息
def get_license_plate(path):
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car"
f = get_file_content(path)
access_token=get_token()
img = base64.b64encode(f)
params = {"top_num":1, "image": img}
params = urllib.parse.urlencode(params).encode('utf-8')
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:
# print (content.decode("utf-8"))
cars = json.loads(content.decode("utf-8"))
strover = '识别结果:'
i = 1
for car in cars['result']:
strover += '{} 车型:{} \n 年份:{}\n 准确率:{}\n'.format(i,car['name'],car['year'],car['score'])
i += 1
print (strover)
return content
else:
return ''
image_path='F:\paddle\m.jpg'
get_license_plate(image_path)