face_recognition使用python調(diào)用記錄
一、查看本機(jī)配置和檢查dlib是否能用gpu,不能用gpu也行,就是處理速度不同,不在乎的話以下檢查可跳過。
我的顯卡:GTX750TI
本機(jī)原來就有裝cuda、cudnn(原來供tensorflow gpu使用)
1、查看cuda版本:
命令行輸入:nvcc --version

查到是v10.0版本;
2、查看cudnn版本
輸入文件地址打開查看
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\include\cudnn.h


查到是7.6.5版本。
2、dlib是本地編譯安裝的(看我之前安裝配置的視頻可見,據(jù)說只有本地編譯才能使用GPU)
輸入命令查看dlib是否能用GPU:
>python
>>> import dlib
>>> print(dlib.DLIB_USE_CUDA)

OK可以使用gpu。
順便檢查一下tensorflow版本,這步是多余的,我只是忘了我裝的TF版本。
>>> tf.__version__

二、開始測(cè)試python調(diào)用face_recognition功能
1、打開python編輯器(我用的是jupyter lab,需安裝。)
在做測(cè)試的工程文件附近空白處按住shift鍵,同時(shí)點(diǎn)擊鼠標(biāo)右鍵,在彈出菜單點(diǎn)擊箭頭處打開命令行終端,輸入jupyter lab回車執(zhí)行:


即可打開編輯器,新建一個(gè)可即時(shí)運(yùn)行python3的文件mian.ipynb:
2、寫入測(cè)試命令:
import face_recognition#導(dǎo)入人臉識(shí)別庫
import numpy as np
#人臉定位框
image = face_recognition.load_image_file('./pictures/unknown_pictures/1.jpg')#讀取一張圖片
face_locations = face_recognition.face_locations(image)#執(zhí)行檢測(cè)并返回人臉位置
print('檢測(cè)到有 {} 人'.format(len(face_locations)))
print(face_locations)

#人臉對(duì)比
known_image = face_recognition.load_image_file('./pictures/known_people/TaylorSwift.jpg')
known_image_encoding = face_recognition.face_encodings(known_image)
unknown_image = face_recognition.load_image_file('./pictures/unknown_pictures/2.jpg')
unknown_image_encoding = face_recognition.face_encodings(unknown_image)[0]
result = face_recognition.compare_faces(known_image_encoding,unknown_image_encoding)
#print(unknown_image_encoding)
print(result)

#人臉截取
from matplotlib import pyplot as plt#繪圖庫
unknown_image = face_recognition.load_image_file('./pictures/unknown_pictures/4.jpg')#讀取一張圖片
face_locations = face_recognition.face_locations(unknown_image)#執(zhí)行檢測(cè)并返回人臉位置
plt.figure(figsize=(10,10))#figsize里面的系數(shù)越大,畫布越大,當(dāng)然運(yùn)行時(shí)間越長(zhǎng)
plt.imshow(unknown_image)#處理將要顯示的圖片
plt.show()#顯示主圖片
plt.figure(figsize=(10,10))#figsize里面的系數(shù)越大,畫布越大,當(dāng)然運(yùn)行時(shí)間越長(zhǎng)
for i,face_location in enumerate(face_locations):
??? top, right, bottom, left = face_location
??? #print(i,top, right, bottom, left)
??? plt.subplot(350+i+1)
??? plt.imshow(unknown_image[top:bottom,left:right])#處理將要顯示經(jīng)切片的圖片,numpy.ndarray的切片方法
plt.show()#顯示圖片
type(unknown_image)

#人臉畫框,注釋
from matplotlib import pyplot as plt#繪圖庫
unknown_image = face_recognition.load_image_file('./pictures/unknown_pictures/4.jpg')#讀取一張圖片
face_locations = face_recognition.face_locations(unknown_image, number_of_times_to_upsample=0, model="cnn")#執(zhí)行HOG模型檢測(cè)并返回人臉位置(相對(duì)慢),使用神經(jīng)網(wǎng)絡(luò)檢測(cè)number_of_times_to_upsample=0, model="cnn",初加載會(huì)比較慢,加載后再檢測(cè)就很快了。
plt.figure(figsize=(10,10))#figsize里面的系數(shù)越大,畫布越大,當(dāng)然運(yùn)行時(shí)間越長(zhǎng)
plt.imshow(unknown_image)#處理將要顯示的圖片
for i,face_location in enumerate(face_locations):
??? top, right, bottom, left = face_location
??? #print(i,top, right, bottom, left)
??? #畫定位框,plt.Rectangle((起點(diǎn)),框尺寸)
??? people_color = '#%06x'%np.random.randint(0xffffff)#隨機(jī)6個(gè)十六進(jìn)制的顏色顏色
??? plt.text(left, top-8, i, bbox={'facecolor':people_color, 'alpha':0.5, 'pad':1})#添加注釋
??? plt.gca().add_patch(plt.Rectangle((left, top), bottom - top, right - left,fill=False,linewidth = 2,edgecolor = people_color))#執(zhí)行畫框
plt.show()#顯示圖片
type(unknown_image)

#檢測(cè)并繪制關(guān)鍵點(diǎn)
from matplotlib import pyplot as plt#繪圖庫
image = face_recognition.load_image_file('./pictures/unknown_pictures/10.jpg')#讀取一張圖片
face_landmarks_list = face_recognition.face_landmarks(image)
plt.figure(figsize=(10,10))#figsize里面的系數(shù)越大,畫布越大,當(dāng)然運(yùn)行時(shí)間越長(zhǎng)
plt.imshow(image)#處理將要顯示的圖片
a = face_landmarks_list[0]
for wuguan? in a.values():
??? for sxy in wuguan:
??????? #print(sxy)
??????? plt.scatter(sxy[0], sxy[1], c='b', s=5)#執(zhí)行畫點(diǎn)
plt.show()#顯示圖片

#攝像頭檢測(cè)人臉
import face_recognition
import numpy as np
import CV2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def CV2ImgAddText1(img, text, left, top, textColor=(0, 255, 0), textSize=20):#opencv不支持中文,得用這個(gè)函數(shù)解決
??? fontText = ImageFont.truetype("./simsun.ttc", textSize)
??? img_pil = Image.fromarray(img)
??? draw = ImageDraw.Draw(img_pil)
??? draw.text((left, top), text, fill = textColor, font=fontText)
??? img = np.array(img_pil)
??? return img
? ?
# This is a super simple (but slow) example of running face recognition on live video from your webcam.
# There's a second example that's a little more complicated but runs faster.
# PLEASE NOTE: This example requires OpenCV (the `CV2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
# Get a reference to webcam #0 (the default one)
video_capture = CV2.VideoCapture(0)
# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("./pictures/known_people/TaylorSwift.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("./pictures/known_people/Clinton.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
??? obama_face_encoding,
??? biden_face_encoding
]
known_face_names = [
??? "TaylorSwift",
??? "Clinton"
]
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
??? # Grab a single frame of video
??? ret, frame = video_capture.read()
??? # Resize frame of video to 1/4 size for faster face recognition processing
??? small_frame = CV2.resize(frame, (0, 0), fx=0.25, fy=0.25)
??? # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
??? rgb_small_frame = small_frame[:, :, ::-1]
??? # Only process every other frame of video to save time
??? if process_this_frame:
??????? # Find all the faces and face encodings in the current frame of video
??????? face_locations = face_recognition.face_locations(rgb_small_frame, model="cnn")#使用神經(jīng)網(wǎng)絡(luò)檢測(cè)
??????? face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
??????? face_names = []
??????? for face_encoding in face_encodings:
??????????? # See if the face is a match for the known face(s)
??????????? matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
??????????? name = "Unknown"
??????????? # # If a match was found in known_face_encodings, just use the first one.
??????????? # if True in matches:
??????????? #???? first_match_index = matches.index(True)
??????????? #???? name = known_face_names[first_match_index]
??????????? # Or instead, use the known face with the smallest distance to the new face
??????????? face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
??????????? best_match_index = np.argmin(face_distances)
??????????? if matches[best_match_index]:
??????????????? name = known_face_names[best_match_index]
??????????? face_names.append(name)
??? process_this_frame = not process_this_frame
??? # Display the results
??? for (top, right, bottom, left), name in zip(face_locations, face_names):#[face_locations, face_names]
??????? # Scale back up face locations since the frame we detected in was scaled to 1/4 size
??????? top *= 4
??????? right *= 4
??????? bottom *= 4
??????? left *= 4
??????? # Draw a box around the face
??????? CV2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
??????? # Draw a label with a name below the face
??????? CV2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), CV2.FILLED)
??????? #font = CV2.FONT_HERSHEY_DUPLEX
??????? #CV2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
??????? frame = CV2ImgAddText1(frame, name, left, bottom-25, textColor=(0, 255, 0),textSize=20)#opencv不支持中文,得用這個(gè)函數(shù)解決
??? # Display the resulting image
??? CV2.imshow('Video', frame)
??? # Hit 'q' on the keyboard to quit!
??? if CV2.waitKey(1) & 0xFF == ord('q'):
??????? break
# Release handle to the webcam
video_capture.release()
CV2.destroyAllWindows()

#動(dòng)態(tài)截屏檢測(cè)
from PIL import ImageGrab
import face_recognition
import numpy as np
import CV2
from PIL import Image, ImageDraw, ImageFont
def CV2ImgAddText1(img, text, left, top, textColor=(0, 255, 0), textSize=20):#CV2.putText不支持中文,得用這個(gè)函數(shù)解決
??? fontText = ImageFont.truetype("./simsun.ttc", textSize)
??? img_pil = Image.fromarray(img)
??? draw = ImageDraw.Draw(img_pil)
??? draw.text((left, top), text, fill = textColor, font=fontText)
??? img = np.array(img_pil)
??? return img
? ?
# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("./pictures/known_people/TaylorSwift.jpg")
TaylorSwift_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("./pictures/known_people/Clinton.jpg")
Clinton_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("./pictures/known_people/馬云.jpg")
mayun_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("./pictures/known_people/成龍.jpg")
chenglong_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
??? TaylorSwift_face_encoding,
??? Clinton_face_encoding,
??? mayun_face_encoding,
??? chenglong_face_encoding
]
known_face_names = [
??? "Taylor Swift",
??? "Clinton",
??? "馬云",
??? "成龍"
]
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
??? # Grab a single frame of video
??? frame = np.array(ImageGrab.grab(bbox=(0, 40, 800, 600)))#動(dòng)態(tài)截屏
??? # Resize frame of video to 1/4 size for faster face recognition processing
??? small_frame = CV2.resize(frame, (0, 0), fx=0.45, fy=0.45)
??? # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
??? rgb_small_frame = small_frame
??? # Only process every other frame of video to save time
??? if process_this_frame:
??????? # Find all the faces and face encodings in the current frame of video
??????? face_locations = face_recognition.face_locations(rgb_small_frame, model="cnn")#使用神經(jīng)網(wǎng)絡(luò)檢測(cè)
??????? face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
??????? face_names = []
??????? for face_encoding in face_encodings:
??????????? # See if the face is a match for the known face(s)
??????????? matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.6)
??????????? name = "Unknown"
??????????? # # If a match was found in known_face_encodings, just use the first one.
??????????? # if True in matches:
??????????? #???? first_match_index = matches.index(True)
??????????? #???? name = known_face_names[first_match_index]
??????????? # Or instead, use the known face with the smallest distance to the new face
??????????? face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
??????????? best_match_index = np.argmin(face_distances)
??????????? if matches[best_match_index]:
??????????????? name = known_face_names[best_match_index]
??????????? face_names.append(name)
??? process_this_frame = not process_this_frame
??? # Display the results
??? for (top, right, bottom, left), name in zip(face_locations, face_names):
??????? # Scale back up face locations since the frame we detected in was scaled to 1/4 size
??????? top = int(top * 0.9)
??????? right = int(right * 1)
??????? bottom = int(bottom * 1.1)
??????? left = int(left * 0.98)
??????? # Draw a box around the face
??????? CV2.rectangle(small_frame, (left, top), (right, bottom-5), (10, 0, 100), 1)
??????? # Draw a label with a name below the face
??????? CV2.rectangle(small_frame, (left, bottom - 10), (right, bottom), (10, 0, 100), CV2.FILLED)
??????? font = CV2.FONT_HERSHEY_DUPLEX
??????? #CV2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
??????? small_frame = CV2ImgAddText1(small_frame, name, left, bottom-10, textColor=(255, 2, 255),textSize=10)#CV2.putText不支持中文,得用這個(gè)函數(shù)解決
??? small_frame = CV2.resize(small_frame, (800, 550))
??? # Display the resulting image
??? CV2.imshow('Video', small_frame[:,:,::-1])
??? # Hit 'q' on the keyboard to quit!
??? if CV2.waitKey(1) & 0xFF == ord('q'):
??????? break
CV2.destroyAllWindows()
