Pages - Menu

2018年3月12日 星期一

Python 3.6 執行 Azure 人臉辨識API

前陣子挺流行的,根據照片判斷出你的年齡。
https://www.how-old.net/
這次要用python來玩玩他的api。


首先,到 微軟網站,申請 人臉識別API ,不用錢,但只有30天。(真掃興)
SNAGHTMLb007df
記住金鑰,二擇一。
可參考他的官方文件
或是另一個 CAVEDU教育團隊技術部落格
真心覺得下面那個寫的比較好,
(p.s:如果使用下面那篇文章,
urllib.urlencode
記得改成 
urllib.parse.urlencode()

然後,httplib  要改成 http.client )
但沒寫到如何直接在電腦上把圖片顯示出來,官方文件有寫到這點。

再來跳到官方文件最下面的function  annotate_image (image_url),顯示出你上傳的照片。
首先要裝的有幾個東西,如果懶得那麼麻煩的話,可以直接安裝 anaconda
是之後要玩Tensorflow的時候發現的,他的優點據說是 包含了各種基本的dll,
不用一個一個安裝,可參考 ithome 的網友寫的文章。
回到正題,官方文件上面說要這些東西,但python3.6有些地方有點小變動。

import matplotlib.pyplot as plt
from PIL import Image
from matplotlib import patches
from io import BytesIO


1.首先是 matplotlib ,這是一個畫圖的lib,安裝方式是 參考 這裡
重點只有一個,到 https://pypi.python.org/pypi/matplotlib/ 這裡下載 屬於你的python版本,以及位元
安裝方式也差不多 ,使用pip3 安裝
2.安裝PIL ,安裝方式 參考 stackoverflow
重點依舊,到 https://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow ,找pillow屬於你的版本以及位元。
3.最後官方文件只要最下面那段  annotate_image (image_url) 就能跑了,
但記得加上plt.show()

附上完整程式碼。如果不呼叫function的話,右邊會看到json列表。
但呼叫function的話,則看不到json列表。應該是可以一起呈現,但只有30天…算了。

import http.client, urllib, base64, json
from io import BytesIO
from PIL import Image
from matplotlib import patches
import requests
import matplotlib.pyplot as plt
import numpy as np
###############################################
#### Update or verify the following values. ###
###############################################
# Replace the subscription_key string value with your valid subscription key.
subscription_key = 'aaaaaabbbbbbbcccccc'   #填入Face API金鑰,任一組都可以
# Replace or verify the region.
#
# You must use the same region in your REST API call as you used to obtain your subscription keys.
# For example, if you obtained your subscription keys from the westus region, replace
# "westcentralus" in the URI below with "westus".
#
# NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
# a free trial subscription key, you should not need to change this region.
uri_base = 'westcentralus.api.cognitive.microsoft.com'
face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'
# Request headers.
headers = {
     'Content-Type': 'application/json',
     'Ocp-Apim-Subscription-Key': subscription_key,
}
# Request parameters.
params = urllib.parse.urlencode({
     'returnFaceId': 'true',
     'returnFaceLandmarks': 'false',
     'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
})
# The URL of a JPEG image to analyze.
body = "{'url':'https://i.imgur.com/ywVy3Yy.jpg'}"
#
try:
     # Execute the REST API call and get the response.
     conn = http.client.HTTPSConnection('westcentralus.api.cognitive.microsoft.com')
     conn.request("POST", "/face/v1.0/detect?%s" % params, body, headers)
     response = conn.getresponse()
     data = response.read()
    # 'data' contains the JSON data. The following formats the JSON data for display.
     parsed = json.loads(data)
     print("Response:")
     print(json.dumps(parsed, sort_keys=True, indent=2))
     print(parsed[0]["faceAttributes"]["smile"])   #第一張臉的 smile 強度
     conn.close()
except Exception as e:
     print("[Errno {0}] {1}".format(e.errno, e.strerror))

#顯示圖片
def annotate_image(image_url):
     response = requests.post(face_api_url, params=params, headers=headers, json={"url": image_url})
     faces = response.json()
    image_file = BytesIO(requests.get(image_url).content)
     image = Image.open(image_file)
    plt.figure(figsize=(8,8))
     ax = plt.imshow(image, alpha=0.6)
     for face in faces:
         fr = face["faceRectangle"]
         fa = face["faceAttributes"]
         origin = (fr["left"], fr["top"])
         p = patches.Rectangle(origin, fr["width"], \
                               fr["height"], fill=False, linewidth=2, color='b')
         ax.axes.add_patch(p)
         plt.text(origin[0], origin[1], "%s, %d"%(fa["gender"].capitalize(), fa["age"]), \
                  fontsize=20, weight="bold", va="bottom")
     plt.axis("off")
     plt.show()
annotate_image("https://i.imgur.com/ywVy3Yy.jpg")

沒有留言:

張貼留言