2017-05-23 19 views
0

我一直在編寫python代碼來傳遞包含圖像的文件夾,以便使用Cognitive Vision API進行分析。當我在網上託管的任何圖像使用URL時,我的代碼工作正常。從本地機器上傳圖像到Microsoft Cognitive Vision的Python方法

但是,我從本地機器傳遞圖像時遇到了一些困難。我試圖將文件路徑轉換爲URL使用:

imageurl = pathlib.Path(path).as_uri() 

有沒有辦法做到這一點?我有大約2000張圖片可供分析。

這篇文章Uploading an image to Microsoft Cognitive Services?提供了一些有關如何使用C#做到這一點,但我沒有找到任何類似的Python文件。

在此先感謝。

+0

剛開作爲一個URL路徑不會奇蹟般地使其可在互聯網上。是否有一個原因,你只是不上傳圖像的地方? – kindall

+0

我嘗試上傳Dropbox上的圖像,但上傳後圖像文件名稱發生更改。我有一個包含所有圖像文件名的列表,但如果文件名被更改,我不能使用該列表。 – SvckG

回答

1

計算機視覺API文檔指出以下幾點:

請求正文:

輸入POST體內通過。支持的輸入法:原始圖像二進制或圖像URL。

因此,如果圖像無法在線獲取(通過URL),則需要將原始二進制文件作爲POST請求的主體傳遞。

下面是一個使用Requests庫的示例。

import requests 

img_filename = '<your image path and filename>' 
with open(img_filename, 'rb') as f: 
    img_data = f.read() 

# you'll need to define the following variables yourself: 
# - params 
# - header 

r = requests.post(api_url, 
        params=params, 
        headers=header, 
        data=img_data) 

我也有一個博客貼子,可能會幫助你:Using Microsoft Cognitive Services to perform OCR on images。這包含Python中的示例代碼,用於上傳圖像並檢索結果。它使用計算機視覺API的OCR部分,但它應該與您要做的相似。

+0

謝謝,我看了你的博客文章。我使用https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze作爲api_url,但它導致了對url的錯誤請求:https://westus.api.cognitive.microsoft.com/vision /v1.0/analyze?language=en&visualFeatures=Description%2C+Categories%2C+color%2C+adult – SvckG

+0

謝謝@Kristoff,它現在可以工作 – SvckG

2

此外,之前所說的需要在'標題'部分從'json'更改爲'octet-stream'。遵循文檔樣式,它應該看起來像這樣。

headers = { 
    'Content-Type': 'application/octet-stream', 
    'Ocp-Apim-Subscription-Key': 'XXXXXXX', 
} 
try:  
    body = open('User/........', "rb").read() 
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com') 
    conn.request("POST", "/emotion/v1.0/recognize?%s" % body, headers) 
    response = conn.getresponse() 
    data = response.read() 
    print(data) 
    conn.close() 
except Exception as e: 
    print(e.args) 
+0

對我而言很棒 – Selva

2

在這裏你去:

import urllib, json 
import requests 

img_filename = 'RH_Louise_Lillian_Gish.jpg' 
with open(img_filename, 'rb') as f: 
    img_data = f.read() 

# Replace the subscription_key string value with your valid subscription key. 
subscription_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX' 

## Request headers. 
header = { 
    'Content-Type': 'application/octet-stream', 
    'Ocp-Apim-Subscription-Key': subscription_key, 
} 

# Request parameters. 
params = urllib.urlencode({ 
    'returnFaceId': 'true', 
    'returnFaceLandmarks': 'false', 
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', 
}) 

api_url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?%s"%params 

r = requests.post(api_url, 
#     params=params, 
        headers=header, 
        data=img_data) 

print (r.json()) 
相關問題