Win7環境下VS2015+Python 2.7 編譯人臉識別開源庫 face_recognition

巧攝ONE裡發表於2018-09-20

最近在研究一個人臉識別開源框架face_recognition,編譯需要依賴 dlib、boost、cmake 等相關環境,在編譯的時候,踩了一大堆坑,網上資料大都不是很全面再加上 Windows 環境下去配置這些本身就比 Liunx 或 Mac下配置要相對麻煩一些。如果你是準備在 Windows 環境下編譯,就做好準備踩坑吧~~~

系統環境

  • Windows 7
  • Python 2.7.14
  • VS2015

安裝步驟

1. 首先github.com/davisking/d…  下載整個zip

git clone https://github.com/davisking/dlib](https://github.com/davisking/dlib
複製程式碼

2. 前置的一些python庫要安裝, scipy, numpy+mkl  這兩個用pip安裝可能會蛋疼, www.lfd.uci.edu/~gohlke/pyt… 到這裡面找對應版本的wheel, 然後用easy_install就KO了

3. 安裝Boost  sourceforge.net/projects/bo…  下載boost-binaries, 最新的,直接點選exe程式等待安裝完畢, 正常的話安裝的目錄是 X:\local\boost_1_XX_X (保持版本名一致, 也就是XX_X別改)

4. 這一步也貌似可以不用  系統變數加上 VS2015的位置  新建一個

VS140COMNTOOLS 值  X:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\
複製程式碼

5. 去到Boost下面, 雙擊一下 bootstrap.bat , 執行OK之後boost_1_66_0\tools\build資料夾下找到以下兩個檔案

Win7環境下VS2015+Python 2.7 編譯人臉識別開源庫 face_recognition

然後開啟一個命令列,定位到這個資料夾,執行命令:

b2 install
複製程式碼

執行完之後再執行下面命令:

 b2 -a --with-python address-model=64 toolset=msvc runtime-link=static 
複製程式碼

成功後能找到 stage 資料夾

6.在系統環境配置好下面兩個環境變數

BOOST_ROOT=C:\local\boost_X_XX_X

BOOST_LIBRARYDIR=C:\local\boost_X_XX_X\stage\lib 

複製程式碼

最後執行以下命令:

python setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDA
複製程式碼

CUDA這個, 主要是用在有顯示卡的機器學習, 如果沒有可以不加 完成! 開啟python shell 試一下 import dlib 沒問題就可以

pip install face_recognition
複製程式碼

安裝成功之後,我們可以在python中正常 import face_recognition 了

Win7環境下VS2015+Python 2.7 編譯人臉識別開源庫 face_recognition

編寫人臉檢測程式

此demo主要展示了識別指定圖片中人臉的特徵資料,下面就是人臉的八個特徵,我們就是要獲取特徵資料

    'chin',
    'left_eyebrow',
    'right_eyebrow',
    'nose_bridge',
    'nose_tip',
    'left_eye',
    'right_eye',
    'top_lip',
    'bottom_lip'
複製程式碼

人臉檢測程式碼

# -*- coding: utf-8 -*-
# 自動識別人臉特徵
# filename : find_facial_features_in_picture.py

# 匯入pil模組 ,可用命令安裝 apt-get install python-Imaging
from PIL import Image, ImageDraw
# 匯入face_recogntion模組,可用命令安裝 pip install face_recognition
import face_recognition

# 將jpg檔案載入到numpy 陣列中
image = face_recognition.load_image_file("mayun.jpg")

#查詢影象中所有面部的所有面部特徵
face_landmarks_list = face_recognition.face_landmarks(image)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))

for face_landmarks in face_landmarks_list:

   #列印此影象中每個面部特徵的位置
    facial_features = [
        'chin',
        'left_eyebrow',
        'right_eyebrow',
        'nose_bridge',
        'nose_tip',
        'left_eye',
        'right_eye',
        'top_lip',
        'bottom_lip'
    ]

    for facial_feature in facial_features:
        print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))

   #讓我們在影象中描繪出每個人臉特徵!
    pil_image = Image.fromarray(image)
    d = ImageDraw.Draw(pil_image)

    for facial_feature in facial_features:
        d.line(face_landmarks[facial_feature], width=5)

    pil_image.show() 
複製程式碼

執行結果: 自動識別圖片中的人臉,並且識別它的特徵

原圖:

原圖

執行效果:

執行結果

編寫人臉識別程式

注意:這裡使用了 python-opencv,一定要配置好了opencv才能執行成功。 opencv選擇跟自己python版本相匹配的版本,可以在這個網站(www.lfd.uci.edu/~gohlke/pyt… .whl(我的python版本是2.7所以選擇該版本安裝),安裝完成之後,開啟 cmd 輸入 import cv2 沒有提示任何錯誤說明安裝成功。

opencv安裝成功

# -*- coding: utf-8 -*-
#

# 檢測人臉
import face_recognition
import cv2

# 讀取圖片並識別人臉
img = face_recognition.load_image_file("mayun.jpeg")
face_locations = face_recognition.face_locations(img)
print face_locations

# 呼叫opencv函式顯示圖片
img = cv2.imread("mayun.jpeg")
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()
複製程式碼

執行結果: 程式會讀取當前目錄下指定的圖片,然後識別其中的人臉,並標註每個人臉。

人臉識別結果

攝像頭實時識別人臉

此處因為公司桌上型電腦沒有攝像頭,所以用的Mac上執行這個demo,配置都是差不多的,環境配置好,執行下面程式碼即可

# -*- coding: utf-8 -*-
# 攝像頭實時識別人臉
import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)
# 載入本地圖片
xhb_img = face_recognition.load_image_file("xhb.jpg")
xhb_face_encoding = face_recognition.face_encodings(xhb_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:
            # 可以自定義設定識別閾值(tolerance)此處設定為0.5,預設為0.6,太小可能識別不出來,太大可能造成識別混淆
            match = face_recognition.compare_faces([xhb_face_encoding], face_encoding,tolerance=0.5)
            
            if match[0]:
                name = "xiaohaibin"
            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()
複製程式碼

執行結果展示

實時人臉識別

相關資料

踩坑

1.解決 cl.exe 找不到的問題

在裝VS2015時,預設是不安裝C++,你需要重新執行setup ,然後選擇modify,選擇 language 下的C++,然後開始安裝,就可以解決問題了 –來自stackoverflow.com/

VS2015配置.png

2.解決執行 pip install face_recognition 出錯,報SSL Error

SSL Error

方案一(推薦):在pip安裝所在資料夾路徑下,創造python檔案(.py)

import os  

ini="""[global] 
index-url = https://pypi.doubanio.com/simple/ 
[install] 
trusted-host=pypi.doubanio.com 
"""  
pippath=os.environ["USERPROFILE"]+"\\pip\\"  

if not os.path.exists(pippath):  
    os.mkdir(pippath)  

with open(pippath+"pip.ini","w+") as f:  
    f.write(ini)  
複製程式碼

在cmd上執行這個.py檔案即可 之後再用pip install安裝指令下載速度會非常快

方案二:修改加大超時時間

pip --default-timeout=100 install -U pip
複製程式碼

再執行下面指令進行安裝

pip --default-timeout=100 install -U face_recognition
複製程式碼

3.Python指令碼報錯AttributeError: ‘module’ object has no attribute’xxx’解決方法

最近在編寫Python指令碼過程中遇到一個問題比較奇怪:Python指令碼完全正常沒問題,但執行總報錯"AttributeError: 'module' object has no attribute 'xxx'"。這其實是.pyc檔案存在問題。

問題定位:

檢視import庫的原始檔,發現原始檔存在且沒有錯誤,同時存在原始檔的.pyc檔案

問題解決方法:

  1. 命名py指令碼時,不要與python預留字,模組名等相同
  2. 刪除該庫的.pyc檔案(因為py指令碼每次執行時均會生成.pyc檔案;在已經生成.pyc檔案的情況下,若程式碼不更新,執行時依舊會走pyc,所以要刪除.pyc檔案),重新執行程式碼;或者找一個可以執行程式碼的環境,拷貝替換當前機器的.pyc檔案即可
如果覺得文章幫到你,喜歡我的文章可以關注我和朋友一起運營的微信公眾號,將會定期推送優質技術文章,求關注~~~
Win7環境下VS2015+Python 2.7 編譯人臉識別開源庫 face_recognition
歡迎加入“大話安卓”技術交流群,一起分享,共同進步
Win7環境下VS2015+Python 2.7 編譯人臉識別開源庫 face_recognition

相關文章