本文目錄一覽:
- 1、dlib庫,怎麼在python中安裝
- 2、如何線上部署用python基於dlib寫的人臉識別演算法
- 3、如何提高python下的dlib人臉檢測速度
- 4、誰用過python中的第三方庫face recognition
dlib庫,怎麼在python中安裝
現進入CMD,然後輸入DOS命令進入setup.py文件所在目錄,然後輸入python setup.py install就搞定了。
如何線上部署用python基於dlib寫的人臉識別演算法
python使用dlib進行人臉檢測與人臉關鍵點標記
Dlib簡介:
首先給大家介紹一下Dlib
Dlib是一個跨平台的C++公共庫,除了線程支持,網路支持,提供測試以及大量工具等等優點,Dlib還是一個強大的機器學習的C++庫,包含了許多機器學習常用的演算法。同時支持大量的數值演算法如矩陣、大整數、隨機數運算等等。
Dlib同時還包含了大量的圖形模型演算法。
最重要的是Dlib的文檔和例子都非常詳細。
Dlib主頁:
這篇博客所述的人臉標記的演算法也是來自Dlib庫,Dlib實現了One Millisecond Face Alignment with an Ensemble of Regression Trees中的演算法
這篇論文非常出名,在谷歌上打上One Millisecond就會自動補全,是CVPR 2014(國際計算機視覺與模式識別會議)上的一篇國際頂級水平的論文。毫秒級別就可以實現相當準確的人臉標記,包括一些半側臉,臉很不清楚的情況,論文本身的演算法十分複雜,感興趣的同學可以下載看看。
Dlib實現了這篇最新論文的演算法,所以Dlib的人臉標記演算法是十分先進的,而且Dlib自帶的人臉檢測庫也很準確,我們項目受到硬體所限,攝像頭拍攝到的畫面比較模糊,而在這種情況下之前嘗試了幾個人臉庫,識別率都非常的低,而Dlib的效果簡直出乎意料。
相對於C++我還是比較喜歡使用python,同時Dlib也是支持python的,只是在配置的時候碰了不少釘子,網上大部分的Dlib資料都是針對於C++的,我好不容易才配置好了python的dlib,這裡分享給大家:
Dlib for python 配置:
因為是用python去開發計算機視覺方面的東西,python的這些科學計算庫是必不可少的,這裡我把常用的科學計算庫的安裝也涵蓋在內了,已經安裝過這些庫的同學就可以忽略了。
我的環境是Ubuntu14.04:
大家都知道Ubuntu是自帶python2.7的,而且很多Ubuntu系統軟體都是基於python2.7的,有一次我系統的python版本亂了,我腦殘的想把python2.7卸載了重裝,然後……好像是提醒我要卸載幾千個軟體來著,沒看好直接回車了,等我反應過來Ctrl + C 的時候系統已經沒了一半了…
所以我發現想要搞崩系統,這句話比rm -rf 還給力…
sudo apt-get remove python2.71
首先安裝兩個python第三方庫的下載安裝工具,ubuntu14.04好像是預裝了easy_install
以下過程都是在終端中進行:
1.安裝pip
sudo apt-get install python-pip1
2.安裝easy-install
sudo apt-get install python-setuptools1
3.測試一下easy_install
有時候系統環境複雜了,安裝的時候會安裝到別的python版本上,這就麻煩了,所以還是謹慎一點測試一下,這裡安裝一個我之前在博客中提到的可以模擬瀏覽器的第三方python庫測試一下。
sudo easy_install Mechanize1
4.測試安裝是否成功
在終端輸入python進入python shell
python1
進入python shell後import一下剛安裝的mechanize
import mechanize1
沒有報錯,就是安裝成功了,如果說沒有找到,那可能就是安裝到別的python版本的路徑了。
同時也測試一下PIL這個基礎庫
import PIL1
沒有報錯的話,說明PIL已經被預裝過了
5.安裝numpy
接下來安裝numpy
首先需要安裝python-dev才可以編譯之後的擴展庫
sudo apt-get install python-dev1
之後就可以用easy-install 安裝numpy了
sudo easy_install numpy1
這裡有時候用easy-install 安裝numpy下載的時候會卡住,那就只能用 apt-get 來安裝了:
sudo apt-get install numpy1
不推薦這樣安裝的原因就是系統環境或者說python版本多了之後,直接apt-get安裝numpy很有可能不知道裝到哪個版本去了,然後就很麻煩了,我有好幾次遇到這個問題,不知道是運氣問題還是什麼,所以風險還是很大的,所以還是盡量用easy-install來安裝。
同樣import numpy 進行測試
python
import numpy1234
沒有報錯的話就是成功了
下面的安裝過程同理,我就從簡寫了,大家自己每步別忘了測試一下
6.安裝scipy
sudo apt-get install python-scipy1
7.安裝matplotlib
sudo apt-get install python-matplotlib1
8.安裝dlib
我當時安裝dlib的過程簡直太艱辛,網上各種說不知道怎麼配,配不好,我基本把stackoverflow上的方法試了個遍,才最終成功編譯出來並且導入,不過聽說18.18更新之後有了setup.py,那真是極好的,18.18我沒有親自配過也不能亂說,這裡給大家分享我配置18.17的過程吧:
1.首先必須安裝libboost,不然是不能使用.so庫的
sudo apt-get install libboost-python-dev cmake1
2.到Dlib的官網上下載dlib,會下載下來一個壓縮包,裡面有C++版的dlib庫以及例子文檔,Python dlib庫的代碼例子等等
我使用的版本是dlib-18.17,大家也可以在我這裡下載:
之後進入python_examples下使用bat文件進行編譯,編譯需要先安裝libboost-python-dev和cmake
cd to dlib-18.17/python_examples
./compile_dlib_python_module.bat 123
之後會得到一個dlib.so,複製到dist-packages目錄下即可使用
這裡大家也可以直接用我編譯好的.so庫,但是也必須安裝libboost才可以,不然python是不能調用so庫的,下載地址:
將.so複製到dist-packages目錄下
sudo cp dlib.so /usr/local/lib/python2.7/dist-packages/1
最新的dlib18.18好像就沒有這個bat文件了,取而代之的是一個setup文件,那麼安裝起來應該就沒有這麼麻煩了,大家可以去直接安裝18.18,也可以直接下載複製我的.so庫,這兩種方法應該都不麻煩~
有時候還會需要下面這兩個庫,建議大家一併安裝一下
9.安裝skimage
sudo apt-get install python-skimage1
10.安裝imtools
sudo easy_install imtools1
Dlib face landmarks Demo
環境配置結束之後,我們首先看一下dlib提供的示常式序
1.人臉檢測
dlib-18.17/python_examples/face_detector.py 源程序:
#!/usr/bin/python# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt## This example program shows how to find frontal human faces in an image. In# particular, it shows how you can take a list of images from the command# line and display each on the screen with red boxes overlaid on each human# face.## The examples/faces folder contains some jpg images of people. You can run# this program on them and see the detections by executing the# following command:# ./face_detector.py ../examples/faces/*.jpg## This face detector is made using the now classic Histogram of Oriented# Gradients (HOG) feature combined with a linear classifier, an image# pyramid, and sliding window detection scheme. This type of object detector# is fairly general and capable of detecting many types of semi-rigid objects# in addition to human faces. Therefore, if you are interested in making# your own object detectors then read the train_object_detector.py example# program. ### COMPILING THE DLIB PYTHON INTERFACE# Dlib comes with a compiled python interface for python 2.7 on MS Windows. If# you are using another python version or operating system then you need to# compile the dlib python interface before you can use this file. To do this,# run compile_dlib_python_module.bat. This should work on any operating# system so long as you have CMake and boost-python installed.# On Ubuntu, this can be done easily by running the command:# sudo apt-get install libboost-python-dev cmake## Also note that this example requires scikit-image which can be installed# via the command:# pip install -U scikit-image# Or downloaded from . import sys
import dlib
from skimage import io
detector = dlib.get_frontal_face_detector()
win = dlib.image_window()
print(“a”);for f in sys.argv[1:]:
print(“a”);
print(“Processing file: {}”.format(f))
img = io.imread(f)
# The 1 in the second argument indicates that we should upsample the image
# 1 time. This will make everything bigger and allow us to detect more
# faces.
dets = detector(img, 1)
print(“Number of faces detected: {}”.format(len(dets))) for i, d in enumerate(dets):
print(“Detection {}: Left: {} Top: {} Right: {} Bottom: {}”.format(
i, d.left(), d.top(), d.right(), d.bottom()))
win.clear_overlay()
win.set_image(img)
win.add_overlay(dets)
dlib.hit_enter_to_continue()# Finally, if you really want to you can ask the detector to tell you the score# for each detection. The score is bigger for more confident detections.# Also, the idx tells you which of the face sub-detectors matched. This can be# used to broadly identify faces in different orientations.if (len(sys.argv[1:]) 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1) for i, d in enumerate(dets):
print(“Detection {}, score: {}, face_type:{}”.format(
d, scores[i], idx[i]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
我把源代碼精簡了一下,加了一下注釋: face_detector0.1.py
# -*- coding: utf-8 -*-import sys
import dlib
from skimage import io#使用dlib自帶的frontal_face_detector作為我們的特徵提取器detector = dlib.get_frontal_face_detector()#使用dlib提供的圖片窗口win = dlib.image_window()#sys.argv[]是用來獲取命令行參數的,sys.argv[0]表示代碼本身文件路徑,所以參數從1開始向後依次獲取圖片路徑for f in sys.argv[1:]: #輸出目前處理的圖片地址
print(“Processing file: {}”.format(f)) #使用skimage的io讀取圖片
img = io.imread(f) #使用detector進行人臉檢測 dets為返回的結果
dets = detector(img, 1) #dets的元素個數即為臉的個數
print(“Number of faces detected: {}”.format(len(dets))) #使用enumerate 函數遍歷序列中的元素以及它們的下標
#下標i即為人臉序號
#left:人臉左邊距離圖片左邊界的距離 ;right:人臉右邊距離圖片左邊界的距離
#top:人臉上邊距離圖片上邊界的距離 ;bottom:人臉下邊距離圖片上邊界的距離
for i, d in enumerate(dets):
print(“dets{}”.format(d))
print(“Detection {}: Left: {} Top: {} Right: {} Bottom: {}”
.format( i, d.left(), d.top(), d.right(), d.bottom())) #也可以獲取比較全面的信息,如獲取人臉與detector的匹配程度
dets, scores, idx = detector.run(img, 1)
for i, d in enumerate(dets):
print(“Detection {}, dets{},score: {}, face_type:{}”.format( i, d, scores[i], idx[i]))
#繪製圖片(dlib的ui庫可以直接繪製dets)
win.set_image(img)
win.add_overlay(dets) #等待點擊
dlib.hit_enter_to_continue()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
分別測試了一個人臉的和多個人臉的,以下是運行結果:
運行的時候把圖片文件路徑加到後面就好了
python face_detector0.1.py ./data/3.jpg12
一張臉的:
兩張臉的:
這裡可以看出側臉與detector的匹配度要比正臉小的很多
2.人臉關鍵點提取
人臉檢測我們使用了dlib自帶的人臉檢測器(detector),關鍵點提取需要一個特徵提取器(predictor),為了構建特徵提取器,預訓練模型必不可少。
除了自行進行訓練外,還可以使用官方提供的一個模型。該模型可從dlib sourceforge庫下載:
arks.dat.bz2
也可以從我的連接下載:
這個庫支持68個關鍵點的提取,一般來說也夠用了,如果需要更多的特徵點就要自己去訓練了。
dlib-18.17/python_examples/face_landmark_detection.py 源程序:
#!/usr/bin/python# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt## This example program shows how to find frontal human faces in an image and# estimate their pose. The pose takes the form of 68 landmarks. These are# points on the face such as the corners of the mouth, along the eyebrows, on# the eyes, and so forth.## This face detector is made using the classic Histogram of Oriented# Gradients (HOG) feature combined with a linear
如何提高python下的dlib人臉檢測速度
Dlib is capable of detecting faces in very small areas (80×80 pixels). You are probably sending raw WebCam frames at approximately 1280×720 resolution, which is not necessary. I recommend from my experience to reduce the frames about a quarter of the original resolution. Yes, 320×180 is fine for Dlib. In consequence you will get 4x speed.
· try turning on the compilation optimizations while building Dlib, you will get significantly improvement in speed.
· Dlib works faster with grayscale images. You do not need the color on the webcam frame. You can use OpenCV to convert into grayscale the previously reduced in size frame.
· Dlib takes its time finding faces but is extremely fast finding landmarks on faces. Only if your Webcam provides a high framerate (24-30fps), you could skip some frames because faces normally doesn’t move so much.
誰用過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啊!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/236546.html