[Face++]Face初探——人臉檢測

通過了強烈的思想鬥爭才把本身拖到圖書館作畢設T^Tpython

anyway, 由於畢設裏面有人臉識別的部分,因此就想找個現成的api先玩玩,因而就找到最近很火的face++:http://www.faceplusplus.com.cn/git

接口什麼的仍是很簡單的,主要就是看它的api開發文檔,最終實現把demo中的hello.py改造以後可以上傳本地的三張圖片進行訓練,而後對新的一幅圖片進行識別,看這幅圖片中的人臉是三張圖片中的哪一張,對於個人畢設而言,這個功能其實就足夠了。修改後的hello.py以下:github

  1 #!/usr/bin/env python2
  2 # -*- coding: utf-8 -*-
  3 # $File: hello.py
  4 
  5 # In this tutorial, you will learn how to call Face ++ APIs and implement a
  6 # simple App which could recognize a face image in 3 candidates.
  7 # 在本教程中,您將瞭解到Face ++ API的基本調用方法,並實現一個簡單的App,用以在3
  8 # 張備選人臉圖片中識別一個新的人臉圖片。
  9 
 10 # You need to register your App first, and enter you API key/secret.
 11 # 您須要先註冊一個App,並將獲得的API key和API secret寫在這裏。
 12 API_KEY = '********'
 13 API_SECRET = '*********'
 14 
 15 # Import system libraries and define helper functions
 16 # 導入系統庫並定義輔助函數
 17 import time
 18 from pprint import pformat
 19 def print_result(hint, result):
 20     def encode(obj):
 21         if type(obj) is unicode:
 22             return obj.encode('utf-8')
 23         if type(obj) is dict:
 24             return {encode(k): encode(v) for (k, v) in obj.iteritems()}
 25         if type(obj) is list:
 26             return [encode(i) for i in obj]
 27         return obj
 28     print hint
 29     result = encode(result)
 30     print '\n'.join(['  ' + i for i in pformat(result, width = 75).split('\n')])
 31 
 32 # First import the API class from the SDK
 33 # 首先,導入SDK中的API類
 34 from facepp import API
 35 from facepp import File
 36 
 37 api = API(API_KEY, API_SECRET)
 38 
 39 # Here are the person names and their face images
 40 # 人名及其臉部圖片
 41 PERSONS = [
 42     ('Yanzi Sun', './syz.jpeg'),
 43     ('Qiaoen Chan', './cqe.jpeg'),
 44     ('Jackie Chan', './jk.jpeg')
 45 ]
 46 TARGET_IMAGE = './cl.jpg'
 47 
 48 # Step 1: Create a group to add these persons in
 49 # 步驟1: 新建一個group用以添加person
 50 api.group.create(group_name = 'forfun')
 51 
 52 # Step 2: Detect faces from those three images and add them to the persons
 53 # 步驟2:從三種圖片中檢測人臉並將其加入person中。 
 54 for (name, path) in PERSONS:
 55     result = api.detection.detect(img = File(path))
 56     print_result('Detection result for {}:'.format(name), result)
 57 
 58     face_id = result['face'][0]['face_id'] 
 59 
 60     # Create a person in the group, and add the face to the person
 61     # 在該group中新建一個person,並將face加入期中
 62     api.person.create(person_name = name, group_name = 'forfun',
 63             face_id = face_id)
 64 
 65 
 66 # Step 3: Train the group.
 67 # Note: this step is required before performing recognition in this group,
 68 # since our system needs to pre-compute models for these persons
 69 # 步驟3:訓練這個group
 70 # 注:在group中進行識別以前必須執行該步驟,以便咱們的系統能爲這些person建模
 71 result = api.recognition.train(group_name = 'forfun', type = 'all')
 72 
 73 # Because the train process is time-consuming, the operation is done
 74 # asynchronously, so only a session ID would be returned.
 75 # 因爲訓練過程比較耗時,因此操做必須異步完成,所以只有session ID會被返回
 76 print_result('Train result:', result)
 77 
 78 session_id = result['session_id']
 79 
 80 # Now, wait before train completes
 81 # 等待訓練完成
 82 while True:
 83     result = api.info.get_session(session_id = session_id)
 84     if result['status'] == u'SUCC':
 85         print_result('Async train result:', result)
 86         break
 87     time.sleep(1)
 88 
 89 #也能夠經過調用api.wait_async(session_id)函數完成以上功能
 90 
 91 
 92 # Step 4: recognize the unknown face image
 93 # 步驟4:識別未知臉部圖片
 94 result = api.recognition.recognize(img = File(TARGET_IMAGE), group_name = 'forfun')
 95 print_result('Recognize result:', result)
 96 print '=' * 60
 97 print 'The person with highest confidence:', \
 98         result['face'][0]['candidate'][0]['person_name']
 99 
100 
101 # Finally, delete the persons and group because they are no longer needed
102 # 最終,刪除無用的person和group
103 api.group.delete(group_name = 'forfun')
104 api.person.delete(person_name = [i[0] for i in PERSONS])
105 
106 # Congratulations! You have finished this tutorial, and you can continue
107 # reading our API document and start writing your own App using Face++ API!
108 # Enjoy :)
109 # 恭喜!您已經完成了本教程,能夠繼續閱讀咱們的API文檔並利用Face++ API開始寫您自
110 # 己的App了!
111 # 旅途愉快 :)

要注意的就是35行,由於原來demo裏面的圖像是經過url獲取的,而這裏須要從本地上傳,因此就要用到facepp.py裏面定義的File類。另外注意12,13行的API_KEY和API_SECRET是經過在網站註冊獲得的。數據庫

其它改動的地方就是圖片的路徑,剩下的都是原來demo中的代碼了。最終的結果以下:api

Detection result for Yanzi Sun:
  {'face': [{'attribute': {'age': {'range': 5, 'value': 30},
                           'gender': {'confidence': 99.9991,
                                      'value': 'Female'},
                           'race': {'confidence': 80.13329999999999,
                                    'value': 'Asian'},
                           'smiling': {'value': 99.3116}},
             'face_id': 'f2790efd530b569cdc505cc2465da34f',
             'position': {'center': {'x': 52.57732, 'y': 41.923077},
                          'eye_left': {'x': 42.224794, 'y': 36.929538},
                          'eye_right': {'x': 62.156701, 'y': 35.701385},
                          'height': 27.692308,
                          'mouth_left': {'x': 42.051031, 'y': 49.590385},
                          'mouth_right': {'x': 63.552577,
                                          'y': 49.841154},
                          'nose': {'x': 53.861856, 'y': 46.203462},
                          'width': 37.113402},
             'tag': ''}],
   'img_height': 260,
   'img_id': '09c7c2d49eb98dc2e90340ef2a6c9531',
   'img_width': 194,
   'session_id': '3a47b91a118d4c7cae9dcaf5ba61eec5',
   'url': None}
Detection result for Qiaoen Chan:
  {'face': [{'attribute': {'age': {'range': 6, 'value': 15},
                           'gender': {'confidence': 99.9974,
                                      'value': 'Female'},
                           'race': {'confidence': 98.2572,
                                    'value': 'Asian'},
                           'smiling': {'value': 2.82502}},
             'face_id': '805b397a72899eda36be3f1dfed73451',
             'position': {'center': {'x': 32.0, 'y': 47.02381},
                          'eye_left': {'x': 26.078067, 'y': 39.870476},
                          'eye_right': {'x': 36.355667, 'y': 39.246726},
                          'height': 38.095238,
                          'mouth_left': {'x': 28.270367, 'y': 59.064881},
                          'mouth_right': {'x': 34.999667,
                                          'y': 59.091369},
                          'nose': {'x': 30.3052, 'y': 49.743036},
                          'width': 21.333333},
             'tag': ''}],
   'img_height': 168,
   'img_id': 'ebee384c2b96399c3f52565682e4c249',
   'img_width': 300,
   'session_id': '5c1623ef71944c11a0efc6b4a698b3b0',
   'url': None}
Detection result for Jackie Chan:
  {'face': [{'attribute': {'age': {'range': 10, 'value': 50},
                           'gender': {'confidence': 99.9967,
                                      'value': 'Male'},
                           'race': {'confidence': 76.5193,
                                    'value': 'Asian'},
                           'smiling': {'value': 96.2044}},
             'face_id': 'f164cc74a49e3d6766c8733ebdfe616d',
             'position': {'center': {'x': 50.166667, 'y': 37.202381},
                          'eye_left': {'x': 45.798, 'y': 32.12381},
                          'eye_right': {'x': 53.721333, 'y': 30.344464},
                          'height': 31.547619,
                          'mouth_left': {'x': 46.665333, 'y': 46.910298},
                          'mouth_right': {'x': 54.770667,
                                          'y': 45.298393},
                          'nose': {'x': 49.889667, 'y': 39.642143},
                          'width': 17.666667},
             'tag': ''}],
   'img_height': 168,
   'img_id': 'd2ef3d2bd1d907fa15130f505300226e',
   'img_width': 300,
   'session_id': 'c7d498450b28453f8f90135ca92a327c',
   'url': None}
Train result:
  {'session_id': '041678d25ac94c2689396d0e6a660302'}
Async train result:
  {'create_time': 1438667400,
   'finish_time': 1438667400,
   'result': {'success': True},
   'session_id': '041678d25ac94c2689396d0e6a660302',
   'status': 'SUCC'}
Recognize result:
  {'face': [{'candidate': [{'confidence': 10.85891,
                            'person_id': '476ec2d1e98b8da80bf661a5241b85fd',
                            'person_name': 'Jackie Chan',
                            'tag': ''},
                           {'confidence': 0.24913,
                            'person_id': '0ef10cf989df7888f376fc54e339b93a',
                            'person_name': 'Yanzi Sun',
                            'tag': ''},
                           {'confidence': 0.0,
                            'person_id': 'a8070f1d28f28fffbb45491da06f3620',
                            'person_name': 'Qiaoen Chan',
                            'tag': ''}],
             'face_id': 'e9b0968077ae7a40ff9eebffadec1520',
             'position': {'center': {'x': 44.5, 'y': 29.75},
                          'eye_left': {'x': 40.519167, 'y': 24.590125},
                          'eye_right': {'x': 47.810167, 'y': 23.993575},
                          'height': 23.0,
                          'mouth_left': {'x': 40.731833, 'y': 35.77625},
                          'mouth_right': {'x': 47.273167, 'y': 35.041},
                          'nose': {'x': 45.096167, 'y': 31.58725},
                          'width': 15.333333}}],
   'session_id': 'dbbabdf0e75d49ff8674f136f0c06bdd'}
============================================================
The person with highest confidence: Jackie Chan

我給了三張訓練圖片:syz.jpeg, cqe.jpeg, jk.jpeg分別表明三個明星,最後一個是Jackie Chan,測試圖片也給的Jackie Chan,最終仍是準確的檢測和識別出來了。session

最後要注意python是腳本語言,因此沒有編譯的過程,上述代碼也沒有錯誤處理的過程,因此若是程序出現了bug會直接中止執行,那麼就沒辦法執行103,104行刪除group和person的代碼了。這個形成的影響就是再次運行上述代碼的時候,雲端數據庫裏面仍然有上一次的group和person,而同一個app裏面是不容許的,就會報「NAME_EXIST」的錯誤,這時候一種辦法是運行demo下面的cmdtool.py,在出現的交互式命令行裏面用下面的代碼手動刪除建立的group和person:app

api.group.delete(group_name = 'forfun')
api.person.delete(person_name='Jackie Chan')
api.person.delete(person_name='Qiaoen Chan')
api.person.delete(person_name='Yanzi Sun')

參考:異步

[1]Face++主頁:http://www.faceplusplus.com.cn/async

[2]Face++開發者文檔:http://www.faceplusplus.com.cn/api-overview/ide

[3]Face++ python sdk: https://github.com/FacePlusPlus/facepp-python-sdk

相關文章
相關標籤/搜索