本文目錄一覽:
人臉識別為什麼用python開發
可以使用OpenCV,OpenCV的人臉檢測功能在一般場合還是不錯的。而ubuntu正好提供了python-opencv這個包,用它可以方便地實現人臉檢測的代碼。
寫代碼之前應該先安裝python-opencv:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# face_detect.py
# Face Detection using OpenCV. Based on sample code from:
#
# Usage: python face_detect.py image_file
import sys, os
from opencv.cv import *
from opencv.highgui import *
from PIL import Image, ImageDraw
from math import sqrt
def detectObjects(image):
“””Converts an image to grayscale and prints the locations of any faces found”””
grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
cvCvtColor(image, grayscale, CV_BGR2GRAY)
storage = cvCreateMemStorage(0)
cvClearMemStorage(storage)
cvEqualizeHist(grayscale, grayscale)
cascade = cvLoadHaarClassifierCascade(
‘/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml’,
cvSize(1,1))
faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.1, 2,
CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20))
result = []
for f in faces:
result.append((f.x, f.y, f.x+f.width, f.y+f.height))
return result
def grayscale(r, g, b):
return int(r * .3 + g * .59 + b * .11)
def process(infile, outfile):
image = cvLoadImage(infile);
if image:
faces = detectObjects(image)
im = Image.open(infile)
if faces:
draw = ImageDraw.Draw(im)
for f in faces:
draw.rectangle(f, outline=(255, 0, 255))
im.save(outfile, “JPEG”, quality=100)
else:
print “Error: cannot detect faces on %s” % infile
if __name__ == “__main__”:
process(‘input.jpg’, ‘output.jpg’)
如何使用Python,基於OpenCV與Face++實現人臉解鎖的功能
近幾天微軟的發布會上講到了不少認臉解鎖的內容,經過探索,其實利用手頭的資源我們完全自己也可以完成這樣一個過程。
本文講解了如何使用Python,基於OpenCV與Face++實現人臉解鎖的功能。
本文基於Python 2.7.11,Windows 8.1 系統。
主要內容
Windows 8.1上配置OpenCV
OpenCV的人臉檢測應用
使用Face++完成人臉辨識(如果你想自己實現這部分的功能,可以借鑒例如這個項目)
Windows 8.1上配置OpenCV
入門的時候配置環境總是一個非常麻煩的事情,在Windows上配置OpenCV更是如此。
既然寫了這個推廣的科普教程,總不能讓讀者卡在環境配置上吧。
下面用到的文件都可以在這裡(提取碼:b6ec)下載,但是注意,目前OpenCV僅支持Python2.7。
將cv2加入site-packages
將下載下來的cv2.pyd文件放入Python安裝的文件夾下的Libsite-packages目錄。
就我的電腦而言,這個目錄就是C:/Python27/Lib/site-packages/。
記得不要直接使用pip安裝,將文件拖過去即可。
安裝numpy組件
在命令行下進入到下載下來的文件所在的目錄(按住Shift右鍵有在該目錄打開命令行的選項)
鍵入命令:
1
pip install numpy-1.11.0rc2-cp27-cp27m-win32.whl
如果你的系統或者Python不適配,可以在這裡下載別的輪子。
測試OpenCV安裝
在命令行鍵入命令:
1
python -c “import cv2”
如果沒有出現錯誤提示,那麼cv2就已經安裝好了。
OpenCV的人臉檢測應用
人臉檢測應用,簡而言之就是一個在照片里找到人臉,然後用方框框起來的過程(我們的相機經常做這件事情)
那麼具體而言就是這樣一個過程:
獲取攝像頭的圖片
在圖片中檢測到人臉的區域
在人臉的區域周圍繪製方框
獲取攝像頭的圖片
這裡簡單的講解一下OpenCV的基本操作。
以下操作是打開攝像頭的基本操作:
1
2
3
4
5
6
7
#coding=utf8
import cv2
# 一般筆記本的默認攝像頭都是0
capInput = cv2.VideoCapture(0)
# 我們可以用這條命令檢測攝像頭是否可以讀取數據
if not capInput.isOpened(): print(‘Capture failed because of camera’)
那麼怎麼從攝像頭讀取數據呢?
1
2
3
4
5
6
7
8
# 接上段程序
# 現在攝像頭已經打開了,我們可以使用這條命令讀取圖像
# img就是我們讀取到的圖像,就和我們使用open(‘pic.jpg’, ‘rb’).read()讀取到的數據是一樣的
ret, img = capInput.read()
# 你可以使用open的方式存儲,也可以使用cv2提供的方式存儲
cv2.imwrite(‘pic.jpg’, img)
# 同樣,你可以使用open的方式讀取,也可以使用cv2提供的方式讀取
img = cv2.imread(‘pic.jpg’)
為了方便顯示圖片,cv2也提供了顯示圖片的方法:
1
2
3
4
5
6
# 接上段程序
# 定義一個窗口,當然也可以不定義
imgWindowName = ‘ImageCaptured’
imgWindow = cv2.namedWindow(imgWindowName, cv2.WINDOW_NORMAL)
# 在窗口中顯示圖片
cv2.imshow(imgWindowName, img)
當然在完成所有操作以後需要把攝像頭和窗口都做一個釋放:
1
2
3
4
5
# 接上段程序
# 釋放攝像頭
capInput.release()
# 釋放所有窗口
cv2.destroyAllWindows()
在圖片中檢測到人臉的區域
OpenCV給我們提供了已經訓練好的人臉的xml模板,我們只需要載入然後比對即可。
1
2
3
4
5
6
7
8
# 接上段程序
# 載入xml模板
faceCascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
# 將圖形存儲的方式進行轉換
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用模板匹配圖形
faces = faceCascade.detectMultiScale(gray, 1.3, 5)
print(faces)
在人臉的區域周圍繪製方框
在上一個步驟中,faces中的四個量分別為左上角的橫坐標、縱坐標、寬度、長度。
所以我們根據這四個量很容易的就可以繪製出方框。
1
2
3
# 接上段程序
# 函數的參數分別為:圖像,左上角坐標,右下角坐標,顏色,寬度
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
成果
根據上面講述的內容,我們現在已經可以完成一個簡單的人臉辨認了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#coding=utf8
import cv2
print(‘Press Esc to exit’)
faceCascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
imgWindow = cv2.namedWindow(‘FaceDetect’, cv2.WINDOW_NORMAL)
def detect_face():
capInput = cv2.VideoCapture(0)
# 避免處理時間過長造成畫面卡頓
nextCaptureTime = time.time()
faces = []
if not capInput.isOpened(): print(‘Capture failed because of camera’)
while 1:
ret, img = capInput.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if nextCaptureTime time.time():
nextCaptureTime = time.time() + 0.1
faces = faceCascade.detectMultiScale(gray, 1.3, 5)
if faces:
for x, y, w, h in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow(‘FaceDetect’, img)
# 這是簡單的讀取鍵盤輸入,27即Esc的acsii碼
if cv2.waitKey(1) 0xFF == 27: break
capInput.release()
cv2.destroyAllWindows()
if __name__ == ‘__main__’:
detect_face()
使用Face++完成人臉辨識
第一次認識Face++還是因為支付寶的人臉支付,響應速度還是非常讓人滿意的。
現在只需要免費註冊一個賬號然後新建一個應用就可以使用了,非常方便。
他的官方網址是這個,註冊好之後在這裡的我的應用中創建應用即可。
創建好應用之後你會獲得API Key與API Secret。
Face++的API調用邏輯簡單來說是這樣的:
上傳圖片獲取讀取到的人的face_id
創建Person,獲取person_id(Person中的圖片可以增加、刪除)
比較兩個face_id,判斷是否是一個人
比較face_id與person_id,判斷是否是一個人
上傳圖片獲取face_id
在將圖片通過post方法上傳到特定的地址後將返回一個json的值。
如果api_key, api_secret沒有問題,且在上傳的圖片中有識別到人臉,那麼會存儲在json的face鍵值下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#coding=utf8
import requests
# 這裡填寫你的應用的API Key與API Secret
API_KEY = ”
API_SECRET = ”
# 目前的API網址是這個,你可以在API文檔里找到這些
BASE_URL = ‘httlus.com/v2’
# 使用Requests上傳圖片
url = ‘%s/detection/detect?api_key=%sapi_secret=%sattribute=none’%(
BASE_URL, API_KEY, API_SECRET)
files = {‘img’: (os.path.basename(fileDir), open(fileDir, ‘rb’),
mimetypes.guess_type(fileDir)[0]), }
r = requests.post(url, files = files)
# 如果讀取到圖片中的頭像則輸出他們,其中的’face_id’就是我們所需要的值
faces = r.json().get(‘face’)
print faces
創建Person
這個操作沒有什麼可以講的內容,可以對照這段程序和官方的API介紹。
官方的API介紹可以見這裡,相信看完這一段程序以後你就可以自己完成其餘的API了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 上接上一段程序
# 讀取face_id
if not faces is None: faceIdList = [face[‘face_id’] for face in faces]
# 使用Requests創建Person
url = ‘%s/person/create’%BASE_URL
params = {
‘api_key’: API_KEY,
‘api_secret’: API_SECRET,
‘person_name’: ‘LittleCoder’,
‘face_id’: ‘,’.join(faceIdList), }
r = requests.get(url, params = params)
# 獲取person_id
print r.json.()[‘person_id’]
進度確認
到目前為止,你應該已經可以就給定的兩張圖片比對是否是同一個人了。
那麼讓我們來試著寫一下這個程序吧,兩張圖片分別為』pic1.jpg』, 『pic2.jpg』好了。
下面我給出了我的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def upload_img(fileDir, oneface = True):
url = ‘%s/detection/detect?api_key=%sapi_secret=%sattribute=none’%(
BASE_URL, API_KEY, API_SECRET)
if oneface: url += ‘mode=oneface’
files = {‘img’: (os.path.basename(fileDir), open(fileDir, ‘rb’),
mimetypes.guess_type(fileDir)[0]), }
r = requests.post(url, files = files)
faces = r.json().get(‘face’)
if faces is None:
print(‘There is no face found in %s’%fileDir)
else:
return faces[0][‘face_id’]
def compare(faceId1, faceId2):
url = ‘%s/recognition/compare’%BASE_URL
params = BASE_PARAMS
params[‘face_id1’] = faceId1
params[‘face_id2’] = faceId2
r = requests.get(url, params)
return r.json()
faceId1 = upload_img(‘pic1.jpg’)
faceId2 = upload_img(‘pic2.jpg’)
if face_id1 and face_id2:
print(compare(faceId1, faceId2))
else:
print(‘Please change two pictures’)
成品
到此,所有的知識介紹都結束了,相比大致如何完成這個項目各位讀者也已經有想法了吧。
下面我們需要構思一下人臉解鎖的思路,大致而言是這樣的:
使用一個程序設置賬戶(包括向賬戶中存儲解鎖用的圖片)
使用另一個程序登陸(根據輸入的用戶名測試解鎖)
這裡會有很多重複的代碼,就不再贅述了,你可以在這裡或者這裡(提取碼:c073)下載源代碼測試使用。
這裡是設置賬戶的截圖:
設置賬戶
這裡是登陸的截圖:
登陸
結束語
希望讀完這篇文章能對你有幫助,有什麼不足之處萬望指正(鞠躬)。
誰用過python中的第三方庫face recognition
簡介
該庫可以通過python或者命令行即可實現人臉識別的功能。使用dlib深度學習人臉識別技術構建,在戶外臉部檢測資料庫基準(Labeled Faces in the Wild)上的準確率為99.38%。
在github上有相關的鏈接和API文檔。
在下方為提供的一些相關源碼或是文檔。當前庫的版本是v0.2.0,點擊docs可以查看API文檔,我們可以查看一些函數相關的說明等。
安裝配置
安裝配置很簡單,按照github上的說明一步一步來就可以了。
根據你的python版本輸入指令:
pip install face_recognition11
或者
pip3 install face_recognition11
正常來說,安裝過程中會出錯,會在安裝dlib時出錯,可能報錯也可能會卡在那不動。因為pip在編譯dlib時會出錯,所以我們需要手動編譯dlib再進行安裝。
按照它給出的解決辦法:
1、先下載下來dlib的源碼。
git clone
2、編譯dlib。
cd dlib
mkdir build
cd build
cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
cmake –build1234512345
3、編譯並安裝python的拓展包。
cd ..
python3 setup.py install –yes USE_AVX_INSTRUCTIONS –no DLIB_USE_CUDA1212
注意:這個安裝步驟是默認認為沒有GPU的,所以不支持cuda。
在自己手動編譯了dlib後,我們可以在python中import dlib了。
之後再重新安裝,就可以配置成功了。
根據你的python版本輸入指令:
pip install face_recognition11
或者
pip3 install face_recognition11
安裝成功之後,我們可以在python中正常import face_recognition了。
編寫人臉識別程序
編寫py文件:
# -*- coding: utf-8 -*-
#
# 檢測人臉
import face_recognition
import cv2
# 讀取圖片並識別人臉
img = face_recognition.load_image_file(“silicon_valley.jpg”)
face_locations = face_recognition.face_locations(img)
print face_locations
# 調用opencv函數顯示圖片
img = cv2.imread(“silicon_valley.jpg”)
cv2.namedWindow(“原圖”)
cv2.imshow(“原圖”, img)
# 遍歷每個人臉,並標註
faceNum = len(face_locations)
for i in range(0, faceNum):
top = face_locations[i][0]
right = face_locations[i][1]
bottom = face_locations[i][2]
left = face_locations[i][3]
start = (left, top)
end = (right, bottom)
color = (55,255,155)
thickness = 3
cv2.rectangle(img, start, end, color, thickness)
# 顯示識別結果
cv2.namedWindow(“識別”)
cv2.imshow(“識別”, img)
cv2.waitKey(0)
cv2.destroyAllWindows()12345678910111213141516171819202122232425262728293031323334353637381234567891011121314151617181920212223242526272829303132333435363738
注意:這裡使用了python-OpenCV,一定要配置好了opencv才能運行成功。
運行結果:
程序會讀取當前目錄下指定的圖片,然後識別其中的人臉,並標註每個人臉。
(使用圖片來自美劇矽谷)
編寫人臉比對程序
首先,我在目錄下放了幾張圖片:
這裡用到的是一張喬布斯的照片和一張奧巴馬的照片,和一張未知的照片。
編寫程序:
# 識別圖片中的人臉
import face_recognition
jobs_image = face_recognition.load_image_file(“jobs.jpg”);
obama_image = face_recognition.load_image_file(“obama.jpg”);
unknown_image = face_recognition.load_image_file(“unknown.jpg”);
jobs_encoding = face_recognition.face_encodings(jobs_image)[0]
obama_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.compare_faces([jobs_encoding, obama_encoding], unknown_encoding )
labels = [‘jobs’, ‘obama’]
print(‘results:’+str(results))
for i in range(0, len(results)):
if results[i] == True:
print(‘The person is:’+labels[i])123456789101112131415161718123456789101112131415161718
運行結果:
識別出未知的那張照片是喬布斯的。
攝像頭實時識別
代碼:
# -*- coding: utf-8 -*-
import face_recognition
import cv2
video_capture = cv2.VideoCapture(1)
obama_img = face_recognition.load_image_file(“obama.jpg”)
obama_face_encoding = face_recognition.face_encodings(obama_img)[0]
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
if process_this_frame:
face_locations = face_recognition.face_locations(small_frame)
face_encodings = face_recognition.face_encodings(small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
if match[0]:
name = “Barack”
else:
name = “unknown”
face_names.append(name)
process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
right *= 4
bottom *= 4
left *= 4
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom – 35), (right, bottom), (0, 0, 255), 2)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left+6, bottom-6), font, 1.0, (255, 255, 255), 1)
cv2.imshow(‘Video’, frame)
if cv2.waitKey(1) 0xFF == ord(‘q’):
break
video_capture.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
識別結果:
我直接在手機上百度了幾張圖試試,程序識別出了奧巴馬。
這個庫很cool啊!
原創文章,作者:DGVGG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129958.html