Python基于Dlib的人脸识别系统的实现
之前已经介绍过人脸识别的基础概念,以及基于opencv的实现方式,今天,我们使用dlib来提取128维的人脸嵌入,并使用k临近值方法来实现人脸识别。
人脸识别系统的实现流程与之前是一样的,只是这里我们借助了dlib和face_recognition这两个库来实现。face_recognition是对dlib库的包装,使对dlib的使用更方便。所以首先要安装这2个库。
pip3installdlib pip3installface_recognition
然后,还要安装imutils库
pip3installimutils
我们看一下项目的目录结构:
. ├──dataset │ ├──alan_grant[22entriesexceedsfilelimit,notopeningdir] │ ├──claire_dearing[53entriesexceedsfilelimit,notopeningdir] │ ├──ellie_sattler[31entriesexceedsfilelimit,notopeningdir] │ ├──ian_malcolm[41entriesexceedsfilelimit,notopeningdir] │ ├──john_hammond[36entriesexceedsfilelimit,notopeningdir] │ └──owen_grady[35entriesexceedsfilelimit,notopeningdir] ├──examples │ ├──example_01.png │ ├──example_02.png │ └──example_03.png ├──output │ ├──lunch_scene_output.avi │ └──webcam_face_recognition_output.avi ├──videos │ └──lunch_scene.mp4 ├──encode_faces.py ├──encodings.pickle ├──recognize_faces_image.py ├──recognize_faces_video_file.py ├──recognize_faces_video.py └──search_bing_api.py 10directories,12files
首先,提取128维的人脸嵌入:
命令如下:
python3encode_faces.py--datasetdataset--encodingsencodings.pickle-dhog
记住:如果你的电脑内存不够大,请使用hog模型进行人脸检测,如果内存够大,可以使用cnn神经网络进行人脸检测。
看代码:
#USAGE
#pythonencode_faces.py--datasetdataset--encodingsencodings.pickle
#importthenecessarypackages
fromimutilsimportpaths
importface_recognition
importargparse
importpickle
importcv2
importos
#constructtheargumentparserandparsethearguments
ap=argparse.ArgumentParser()
ap.add_argument("-i","--dataset",required=True,
help="pathtoinputdirectoryoffaces+images")
ap.add_argument("-e","--encodings",required=True,
help="pathtoserializeddboffacialencodings")
ap.add_argument("-d","--detection-method",type=str,default="hog",
help="facedetectionmodeltouse:either`hog`or`cnn`")
args=vars(ap.parse_args())
#grabthepathstotheinputimagesinourdataset
print("[INFO]quantifyingfaces...")
imagePaths=list(paths.list_images(args["dataset"]))
#initializethelistofknownencodingsandknownnames
knownEncodings=[]
knownNames=[]
#loopovertheimagepaths
for(i,imagePath)inenumerate(imagePaths):
#extractthepersonnamefromtheimagepath
print("[INFO]processingimage{}/{}".format(i+1,
len(imagePaths)))
name=imagePath.split(os.path.sep)[-2]
#loadtheinputimageandconvertitfromRGB(OpenCVordering)
#todlibordering(RGB)
image=cv2.imread(imagePath)
rgb=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
#detectthe(x,y)-coordinatesoftheboundingboxes
#correspondingtoeachfaceintheinputimage
boxes=face_recognition.face_locations(rgb,
model=args["detection_method"])
#computethefacialembeddingfortheface
encodings=face_recognition.face_encodings(rgb,boxes)
#loopovertheencodings
forencodinginencodings:
#addeachencoding+nametooursetofknownnamesand
#encodings
knownEncodings.append(encoding)
knownNames.append(name)
#dumpthefacialencodings+namestodisk
print("[INFO]serializingencodings...")
data={"encodings":knownEncodings,"names":knownNames}
f=open(args["encodings"],"wb")
f.write(pickle.dumps(data))
f.close()
输出结果是每张图片输出一个人脸的128维的向量和对于的名字,并序列化到硬盘,供后续人脸识别使用。
识别图像中的人脸:
这里使用KNN方法实现最终的人脸识别,而不是使用SVM进行训练。
命令如下:
python3recognize_faces_image.py--encodingsencodings.pickle --imageexamples/example_01.png
看代码:
#USAGE
#pythonrecognize_faces_image.py--encodingsencodings.pickle--imageexamples/example_01.png
#importthenecessarypackages
importface_recognition
importargparse
importpickle
importcv2
#constructtheargumentparserandparsethearguments
ap=argparse.ArgumentParser()
ap.add_argument("-e","--encodings",required=True,
help="pathtoserializeddboffacialencodings")
ap.add_argument("-i","--image",required=True,
help="pathtoinputimage")
ap.add_argument("-d","--detection-method",type=str,default="cnn",
help="facedetectionmodeltouse:either`hog`or`cnn`")
args=vars(ap.parse_args())
#loadtheknownfacesandembeddings
print("[INFO]loadingencodings...")
data=pickle.loads(open(args["encodings"],"rb").read())
#loadtheinputimageandconvertitfromBGRtoRGB
image=cv2.imread(args["image"])
rgb=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
#detectthe(x,y)-coordinatesoftheboundingboxescorresponding
#toeachfaceintheinputimage,thencomputethefacialembeddings
#foreachface
print("[INFO]recognizingfaces...")
boxes=face_recognition.face_locations(rgb,
model=args["detection_method"])
encodings=face_recognition.face_encodings(rgb,boxes)
#initializethelistofnamesforeachfacedetected
names=[]
#loopoverthefacialembeddings
forencodinginencodings:
#attempttomatcheachfaceintheinputimagetoourknown
#encodings
matches=face_recognition.compare_faces(data["encodings"],
encoding)
name="Unknown"
#checktoseeifwehavefoundamatch
ifTrueinmatches:
#findtheindexesofallmatchedfacestheninitializea
#dictionarytocountthetotalnumberoftimeseachface
#wasmatched
matchedIdxs=[ifor(i,b)inenumerate(matches)ifb]
counts={}
#loopoverthematchedindexesandmaintainacountfor
#eachrecognizedfaceface
foriinmatchedIdxs:
name=data["names"][i]
counts[name]=counts.get(name,0)+1
#determinetherecognizedfacewiththelargestnumberof
#votes(note:intheeventofanunlikelytiePythonwill
#selectfirstentryinthedictionary)
name=max(counts,key=counts.get)
#updatethelistofnames
names.append(name)
#loopovertherecognizedfaces
for((top,right,bottom,left),name)inzip(boxes,names):
#drawthepredictedfacenameontheimage
cv2.rectangle(image,(left,top),(right,bottom),(0,255,0),2)
y=top-15iftop-15>15elsetop+15
cv2.putText(image,name,(left,y),cv2.FONT_HERSHEY_SIMPLEX,
0.75,(0,255,0),2)
#showtheoutputimage
cv2.imshow("Image",image)
cv2.waitKey(0)
实际效果如下:
如果要详细了解细节,请参考:https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/
到此这篇关于Python基于Dlib的人脸识别系统的实现的文章就介绍到这了,更多相关PythonDlib人脸识别内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。