导入需要的包。然后定义几个函数:
def list_images(basePath, contains=None):
return the set of files that are valid
return list_files(basePath, validExts=image_types, contains=contains)
def list_files(basePath, validExts=None, contains=None):
loop over the directory structure
for (rootDir, dirNames, filenames) in os.walk(basePath):
loop over the filenames in the current directory
for filename in filenames:
if the contains string is not none and the filename does not contain
the supplied string, then ignore the file
if contains is not None and filename.find(contains) == -1:
continue
determine the file extension of the current file
ext = filename[filename.rfind(“.”):].lower()
check to see if the file is an image and should be processed
if validExts is None or ext.endswith(validExts):
construct the path to the image and yield it
imagePath = os.path.join(rootDir, filename)
yield imagePath
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
如果高和宽为None则直接返回
if width is None and height is None:
return image
检查宽是否是None
if width is None:
计算高度的比例并并按照比例计算宽度
r = height / float(h)
dim = (int(w * r), height)
高为None
else:
计算宽度比例,并计算高度
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return the resized image
return resized
list_images函数,读取数据集文件夹下面的图片。
resize函数,等比例resize图片。接下来定义一些变量:
dataset_path=‘dataset’
embeddings_path=‘output/embeddings.pickle’
detector_path=‘face_dete_model’
embedding_model=‘nn4.small2.v1.t7’
confidence_low=0.5
dataset_path:数据集路径
embeddings_path:输出编码文件的路径
detector_path:人脸检测模型的路径
embedding_model:编码模型
confidence_low:最低的置信度。
接下来就是代码的最重要的部分:
print(“loading face detector…”)
protoPath = os.path.sep.join([detector_path, “deploy.proto.txt”])
modelPath = os.path.sep.join([detector_path,“res10_300x300