[英]Google Cloud Vision API - Python
我似乎無法在我的谷歌雲視覺代碼中找到添加API密鑰的位置或我需要找到谷歌憑證文件的位置:
import argparse
import base64
import httplib2
import validators
import requests
from apiclient.discovery import build
from oauth2client.client import GoogleCredentials
def main(photo_file):
'''Run a label request on a single image'''
API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/cloud-platform'])
credentials.authorize(http)
service = build('vision', 'v1', http, discoveryServiceUrl=API_DISCOVERY_FILE)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'image_file', help='The image you\'d like to label.')
args = parser.parse_args()
main(args.image_file)
photo_file = "image_of_bottle.jpg"
main(photo_file)
有誰知道我可以在哪里添加API密鑰或找到憑證文件?
編輯:添加了Eray Balkanli推薦的更改,我在通話中添加了我的圖像文件。 我不確定我是否做得正確:
import argparse
import base64
import httplib2
import validators
import requests
from apiclient.discovery import build
from oauth2client.client import GoogleCredentials
def main(photo_file,developerkey):
'''Run a label request on a single image'''
API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/cloud-platform'])
credentials.authorize(http)
service = build('vision', 'v1', http, discoveryServiceUrl=API_DISCOVERY_FILE,developerkey=INSERT API KEY)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'image_file', help='The image you\'d like to label.')
args = parser.parse_args()
main(args.image_file)
photo_file = "image_file.jpg"
main(photo_file,developerkey)
我收到以下錯誤:
usage: googleimagetest_v.4.py [-h] image_file
googleimagetest_v.4.py: error: too few arguments
有誰知道我怎么能解決這個錯誤?
用於對API進行身份驗證的 Google Vision API文檔清楚地提供了如何獲取憑據的分步指南,該頁面的最后一部分介紹了Authenticating with Application Default Credentials
:
應用程序向Google Cloud Platform API服務進行身份驗證的最簡單方法是使用應用程序默認憑據(ADC)。 使用ADC的服務首先在GOOGLE_APPLICATION_CREDENTIALS環境變量中搜索憑據。 除非您特別希望讓ADC使用其他憑據(例如,用戶憑據),否則我們建議您將此環境變量設置為指向您的服務帳戶密鑰文件(創建服務帳戶密鑰時下載的.json文件,如設置服務帳戶。
$ export GOOGLE_APPLICATION_CREDENTIALS = <path_to_service_account_file>
如果重要(如果您尚未注冊),Google會為您提供免費試用訪問權限(365天價值300美元)的雲平台。 它們對Vision API的低價格 imho應該可以讓你為測試做很多事情。
現在,代碼中的錯誤; 即使你對錯誤描述的內容不清楚,看起來你的代碼接受了一個參數,但你試圖運行你的python腳本而沒有一個。 您可以按以下方式運行代碼:
python googleimagetest_v.4.py "image_file.jpg"
並且您不需要以下2行(因為它是對main()
重復調用)
photo_file = "image_file.jpg"
main(photo_file,developerkey)
您已經定義了main()
函數來接受2個參數,但是當您在__main__
部分中調用它時,您傳遞的是一個參數。 您可能也想解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.