使用 OpenCV 与 Face++ 人脸识别

今天看到一篇文章《使用 OpenCV 与 Face++ 实现人脸解锁》,感觉挺好玩,就照着作者的讲解,写了一下。详细内容还请看原作者文章。

 1 # *^_^* coding:utf-8 *^_^*
 2 from __future__ import print_function
 3 
 4 __author__ = 'stone'
 5 __date__ = '16-4-13'
 6 
 7 """
 8 http://www.cnblogs.com/asmer-stone/p/5389383.html
 9 """
10 
11 import cv2
12 import numpy as np
13 import time
14 import requests
15 import os
16 import mimetypes
17 
18 face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
19 API_KEY = 'xxx'
20 API_SECRET = 'xxx'
21 BASE_URL = 'http://apicn.faceplusplus.com/v2'
22 
23 //用opencv检测人脸的函数,注释部分内容是检测并画出人脸区域。
24 def detect_face():    
25     cap = cv2.VideoCapture(0)
26     next_capture_time = time.time()
27     faces = []
28 
29     if not cap.isOpened():
30         print("Capture Opening ERROR!")
31 
32     while 1:
33         ret, img = cap.read()
34 
35         # img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
36         # if next_capture_time < time.time():
37         #     next_capture_time += 0.1
38         #     faces = face_cascade.detectMultiScale(img_gray, 1.3, 5)
39         # if faces is not None:
40         #     for x, y, w, h in faces:
41         #         img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
42         cv2.imshow("face_detect", img)
43         k = cv2.waitKey(1) & 0xFF
44         if k == ord('s'):
45             cv2.imwrite("image/face2.jpg", img)  //打开摄像头按下‘s’键即可保存图片
46         if k == 27:
47             break
48 
49     cap.release()
50     cv2.destroyAllWindows()
51 
52 
53 def update_img(file_dir, oneface=True):  //上传图片到face++ 并返回face_id
54     url = '%s/detection/detect?api_key=%s&api_secret=%s&attribute=none' % (BASE_URL, API_KEY, API_SECRET)
55     if oneface:
56         url += '&mode=oneface'
57     files = {'img': (os.path.basename(file_dir), open(file_dir, 'rb'), mimetypes.guess_type(file_dir)[0])}
58     r = requests.post(url, files=files)
59     faces = r.json().get('face')
60     if faces is None:
61         print("No face")
62     else:
63         return faces[0]['face_id']
64 
65 
66 def compare(faceID1, faceID2):  //比较两张图片中的人脸的相似度函数
67     url = '%s/recognition/compare?api_key=%s&api_secret=%s&face_id1=%s&face_id2=%s' % (
68     BASE_URL, API_KEY, API_SECRET, faceID1, faceID2)
69     r = requests.get(url)
70     return r.json()
71 
72 
73 if __name__ == "__main__":
74     faceID1 = update_img('image/lena.jpg')
75     faceID2 = update_img('image/17-1m.bmp')
76     if faceID2 and faceID1:
77         compare_json = compare(faceID1, faceID2)
78         print(compare_json)
79         if (compare_json['similarity'] > 90):  //相似在90以上打印yes,否则no
80             print("yes")
81         else:
82             print("no")
83     else:
84         print("Something wrong with the pictures!")

 

参考文献:《使用 OpenCV 与 Face++ 实现人脸解锁》:http://python.jobbole.com/84666/

posted @ 2016-04-13 23:45  Fienly  阅读(1468)  评论(0编辑  收藏  举报