本篇文章主要实现了使用API实现基本的image Recognition,基于Python语言:
- 到CloudSight网址注册账号,create 一个project,然后获取到API key,网址:https://cloudsightapi.com/
- 如何运行?将代码保存为py文件,然后再cmd当中进入保存py文件的文件夹,然后输入命令:python xxx.py “photo URL”即可输出识别图片(image Recognition)结果。
- 个人觉得做image Recognition其实是很贵的,如果没有一个很好的硬件设施(GPU),还是找API比较合适,但是API实现的却又不完全是自己想要的功能,所以可能的话还是多了解自己训练模型
- 上代码:
#!usr/bin/env python
#encoding=utf-8
import requests
import sys, getopt
LOCALE = 'zh-CN'
LANGUAGE = 'zh-CN'
def doRequest(imageUrl):
#format of execute: python cloudSightAPI.py "https://pbs.twimg.com/profile_images/525821899/___.jpg"
#input the url of photo
reqUrlA = 'https://api.cloudsightapi.com/image_requests/' # get token
reqUrlB = 'https://api.cloudsightapi.com/image_responses/' # get the final recognition result with token
headers = {
'Authorization' : 'CloudSight mvJS_ZBtk7Z_0dmZiaNjkw',
#'Host' : 'api.cloudsightapi.com',
#'Origin:' : 'http://cloudsightapi.com/',
}
postData = {
'image_request[remote_image_url]' : imageUrl,
'image_request[locale]': 'zh-CN',
'image_request[language]': 'zh-CN',
}
try:
response = requests.post(reqUrlA, headers=headers, data=postData)
except Exception as e:
print ('Error: connection error, please check your Internet and confirm the image url1: %s' % str(e))
sys.exit()
if "error" in response.json():
print ('Error: %s' % response.json()["error"])
# print ('cant recognize the photo')
sys.exit()
else:
token = response.json()['token']
# you may get some response with status 'not completed' for about some times before getting the final result
reqTimes = 20
isNotified = True
while reqTimes > 0:
try:
response = requests.get(reqUrlB + token, headers=headers)
except Exception as e:
print ('Error: connection error, please check your Internet and confirm the image url2: %s'% str(e))
sys.exit()
status = response.json()['status']
#output
if status == 'completed':
print 'RESULT: '
print '\timage url:', imageUrl
print '\timage name:', response.json()['name']
# return response.json()['name']
break
elif status == 'not completed':
if isNotified == True:
print ('recognition in progress')
isNotified = False
reqTimes -= 1
def usage():
print '''
usage:
cloudSightAPI ImageURL
type `cloudSightAPI -h` to get help
'''
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'h')
for op, value in opts:
if op == '-h':
usage()
sys.exit()
if len(args) == 0:
usage()
sys.exit()
except getopt.GetoptError as e:
print 'Error: using invalid parameter -%s' % e.opt
usage()
sys.exit()
imageUrl = sys.argv[1]
doRequest(imageUrl)
if __name__ == '__main__':
main()
实现案例: