face_recognition启动加速——预处理图片

        之前用人脸识别库face_recognition 做人脸识别,根据网上的demo试了试,发现当加入图片过多时,在启动该文件时需要预处理对图像编码的时间会非常长,影响体验,前两天看了CSDN公众号推了一篇文章(链接点这),讲可以先对图片预处理encoding后写入文件,程序启动时加载该文件,于是就写了个脚本,实现读取一个文件夹的人脸图片,并取文件名作为图片人名。稍作记录

预处理脚本,需要一个images文件夹存放图片,与运行脚本在一层目录,运行前请确保已安装pickle,dlib,face_recognition,安装可以参考: https://blog.csdn.net/qq_30460905/article/details/80144731

#read the images and it's image name then pre-encoding 2018.6.23
print("Initialing...")
import os
import time
import pickle
import face_recognition

time_start=time.time()
path = os.getcwd()+'/images'
os.chdir(path)
images_file = os.listdir('.')
know_names = []
know_paths = []
know_encodings = []
print("Reading files from directory...")
for each in images_file:
	name = os.path.splitext(each)[0]
	know_names.append(name)
	image_path = path+'/'+each
	know_paths.append(image_path)
print("Starting encoding!")
#print(know_names)
#print(know_paths)
count = 1
for each_path in know_paths:
	img = face_recognition.load_image_file(each_path)
	#locate face and detection_method 
	print("Encoding the %d picture..." % count)
	#boxes = face_recognition.face_locations(img,model = 'cnn')#hog faster,and cnn more accurate	
	encoding = face_recognition.face_encodings(img)[0]
	#encoding = face_recognition.face_encodings(img,boxes)
	know_encodings.append(encoding)
	count = count+1
#原文中采用字典存储,写入了一个文件,我把它俩分开了
print("Finished encodings,Writing pickle file...")	
#dump images encodings in to face_encodings.pkl file
pickle_encoding_file = open('../face_encodings.pkl','wb')
pickle.dump(know_encodings,pickle_encoding_file)
pickle_encoding_file.close()

#dump images names in to face_names.pkl file
pickle_name_file = open('../face_names.pkl','wb')
pickle.dump(know_names,pickle_name_file)
pickle_name_file.close()
time_end=time.time()
time_take = time_end - time_start
print("It takes %s seconds!" % time_take)
print("All images pretreatment finished!")


能用GPU加速千万别忘了编译dlib时加上cuda选项,不然太慢了,开始没选cuda,后来又重新编译了一遍!

$ cd dlib
$ mkdir build
$ cd build
$ cmake .. -DDLIB_USE_CUDA=1 -DUSE_AVX_INSTRUCTIONS=1
$ cmake --build .
$ cd ..
$ python setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDA

猜你喜欢

转载自blog.csdn.net/qq_30460905/article/details/80864081