【Python】使用Microsoft Azure的人臉API進行本地圖片情緒識別並存入excel
阿新 • • 發佈:2018-05-04
win exce xls 圖片 獲取時間 contain resp 每分鐘 ats
準備工作
首先,需要在Microsoft的主頁(https://azure.microsoft.com/zh-cn/)註冊一個賬號,然後進入門戶去創建新資源,選擇AI+Cognitive Services中的人臉API,填寫相關信息就可以了。
微軟Azure的免費API是限制每分鐘的訪問量與月訪問量的,其他功能倒是沒什麽區別。但是之前創建這個訂閱是不需要綁定信用卡就可以獲取API Key和API Secret的,後來再創建的時候發現必須要綁定Visa信用卡才可以了(?)
總之到這裏,我們拿到了API Key,API Secret和URL。
然後準備好本地待識別情緒的圖片/相片。
代碼
介紹下所使用的第三方庫
——httplib是一個相對底層的http請求模塊
——urllib是接受URL請求的相關模塊
——json (Emmmmmm……我也不知道該怎麽解釋這個)
——xlwt是對excel進行寫入操作的一個庫
——time是對時間進行處理的一個庫,以下代碼中其實就使用了sleep()和localtime()兩個函數,sleep()是用來讓程序暫停幾秒的,localtime()是格式化時間戳為本地的時間
——os是操作系統的相關功能的一個庫,例如用來處理文件和目錄之類的
1 # coding:utf-8 2 # version:python2.7.6 3 # author:Ivy Wong4 5 # 導入相關模塊 6 import httplib, urllib, json 7 import xlwt, time, os 8 9 10 11 12 # 使用micrsoft的api識別情緒 13 def useapi(img): 14 # 定義html的header,這裏Content-type決定了body中的類型,是URL還是文件類型的,這裏的Json支持URL模式 15 headers = { 16 ‘Content-Type‘: ‘application/octet-stream‘, 17 ‘Ocp-Apim-Subscription-Key‘: subscription_key, 18 } 19 20 # 定義返回的內容,包括FaceId,年齡、性別等等 21 params = urllib.urlencode({ 22 ‘returnFaceId‘: ‘true‘, 23 ‘returnFaceLandmarks‘: ‘false‘, 24 ‘returnFaceAttributes‘: ‘age,gender,smile,glasses,emotion‘, 25 }) 26 27 # Call Face API,進行人臉識別 28 try: 29 # Execute the REST API call and get the response. 30 conn = httplib.HTTPSConnection(‘api.cognitive.azure.cn‘) 31 conn.request("POST", "/face/v1.0/detect?%s" % params, img, headers) 32 response = conn.getresponse() 33 data = response.read() 34 35 # ‘data‘ contains the JSON data. The following formats the JSON data for display. 36 parsed = json.loads(data) 37 conn.close() 38 39 except Exception as e: 40 print("[Errno {0}] {1}".format(e.errno, e.strerror)) 41 42 return parsed 43 44 45 # 將json字典寫入excel 46 # 變量用來循環時控制寫入單元格,感覺這種方式有點傻,但暫時想不到優化方法 47 def writeexcel(img, worksheet, row, files_name, path,file_num): 48 parsed = useapi(img) 49 if not parsed: 50 print ‘This picture do not have any face‘ 51 elif ‘error‘ in parsed: 52 print parsed[‘error‘][‘message‘] 53 # 如果是達到每分鐘的限制,就先暫停一分鐘 54 if parsed[‘error‘][‘message‘]==‘Rate limit is exceeded. Try again later.‘: 55 print ‘The file number is ‘ + str(file_num) 56 print ‘The program will be asleep for 60s‘ 57 time.sleep(60) 58 print ‘Now, the program go back to work!‘ 59 writeexcel(img,worksheet,row,files_name,path,file_num) 60 else: 61 for list_item in parsed: 62 # 寫入文件名 63 filename, extension=os.path.splitext(files_name) 64 worksheet.write(row, 0, filename) 65 66 # 寫入時間戳 67 daystamp, timestamp, hourstamp = gettimestamp(path) 68 worksheet.write(row, 1, label=daystamp) 69 worksheet.write(row, 2, label=timestamp) 70 worksheet.write(row,3,hourstamp) 71 72 # 寫入api返回的數據 73 emotion = [] 74 for key1, value1 in list_item.items(): 75 if key1 == ‘faceAttributes‘: 76 for key2, value2 in value1.items(): 77 if key2 == ‘age‘: 78 worksheet.write(row, 5, value2) 79 elif key2 == ‘emotion‘: 80 for key3, value3 in value2.items(): 81 if key3 == ‘anger‘: 82 worksheet.write(row, 8, value3) 83 emotion.append(value3) 84 elif key3 == ‘contempt‘: 85 worksheet.write(row, 9, value3) 86 emotion.append(value3) 87 elif key3 == ‘disgust‘: 88 worksheet.write(row, 10, value3) 89 emotion.append(value3) 90 elif key3 == ‘fear‘: 91 worksheet.write(row, 11, value3) 92 emotion.append(value3) 93 elif key3 == ‘happiness‘: 94 worksheet.write(row, 12, value3) 95 emotion.append(value3) 96 elif key3 == ‘neutral‘: 97 worksheet.write(row, 13, value3) 98 emotion.append(value3) 99 elif key3 == ‘sadness‘: 100 worksheet.write(row, 14, value3) 101 emotion.append(value3) 102 else: 103 worksheet.write(row, 15, value3) 104 emotion.append(value3) 105 elif key2 == ‘gender‘: 106 worksheet.write(row, 6, value2) 107 elif key2 == ‘glasses‘: 108 worksheet.write(row, 7, value2) 109 else: 110 pass 111 elif key1 == ‘faceId‘: 112 worksheet.write(row, 4, value1) 113 else: 114 pass 115 worksheet.write(row, 16, emotion.index(max(emotion))) 116 # 寫入概率最大的情緒,0-sadness,1-neutral,2-contempt,3-disgust,4-anger,5-surprise,6-fear,7-happiness 117 row += 1 118 print ‘Success! The pic ‘ + str(files_name) + ‘ was detected!‘ 119 return row, worksheet 120 121 122 # 獲取時間戳 123 def gettimestamp(path): 124 statinfo = os.stat(path) 125 timeinfo = time.localtime(statinfo.st_ctime) 126 daystamp = str(timeinfo.tm_year) + ‘-‘ + str(timeinfo.tm_mon) + ‘-‘ + str(timeinfo.tm_mday) 127 timestamp = str(timeinfo.tm_hour) + ‘:‘ + str(timeinfo.tm_min) + ‘:‘ + str(timeinfo.tm_sec) 128 hourstamp = timeinfo.tm_hour+timeinfo.tm_min/60.0+timeinfo.tm_sec/3600.0 129 return daystamp, timestamp, hourstamp 130 131 132 subscription_key = ‘your_key‘ 133 uri_base = ‘https://api.cognitive.azure.cn/face/v1.0‘ 134 path = r‘圖片文件夾路徑‘ 135 # 註意:由於我是對同一文件夾下的多個文件夾中的圖片進行識別,所以這個path是圖片所在文件夾的上一級文件夾。文件夾名盡量使用英文與數字,不然可能因為編碼問題報錯 136 # 創建excel 137 workbook = xlwt.Workbook(encoding=‘utf-8‘) 138 139 140 141 for root, dirs, files in os.walk(path, topdown=False): 142 for folder in dirs: 143 144 error_num = 0 145 error_list = [] 146 print ‘Let us start dealing with folder ‘ + folder 147 148 # 創建一個新的sheet 149 worksheet = workbook.add_sheet(folder) 150 # 設置表頭 151 title = [‘PhotoID‘, ‘daystamp‘, ‘timestamp‘, ‘hourstamp‘,‘faceID‘, ‘age‘, ‘gender‘, 152 ‘glasses‘, ‘anger‘, ‘contempt‘,‘disgust‘, ‘fear‘, ‘happiness‘, 153 ‘neutral‘, ‘sadness‘, ‘surprise‘,‘emotion‘] 154 for col in range(len(title)): 155 worksheet.write(0, col, title[col]) 156 157 # 遍歷每個folder裏的圖片 158 row = 1 159 file_num = 1 160 for root2, dirs2, files2 in os.walk(path + ‘\\‘ + folder): 161 for files_name in files2: 162 try: 163 path2 = path + ‘\\‘ + folder + ‘\\‘ + files_name 164 print ‘Now, the program is going to deal with ‘ + folder + ‘ pic‘ + str(files_name) 165 img = open(os.path.expanduser(path2), ‘rb‘) 166 row, worksheet = writeexcel(img, worksheet, row, files_name, path2,file_num) 167 file_num += 1 168 except Exception as e: 169 print e 170 171 172 print ‘The current folder is done.‘ 173 print error_num,error_list 174 175 # 保存文件 176 workbook.save(‘detectface.xls‘) 177 print ‘The program is done!‘
成果
最後生成的excel大概是這個樣子。
其中emotion就是概率最大的情緒,0-sadness,1-neutral,2-contempt,3-disgust,4-anger,5-surprise,6-fear,7-happiness。face++返回的有7種情緒,而azure返回的有8種情緒。
【Python】使用Microsoft Azure的人臉API進行本地圖片情緒識別並存入excel