import cv2
import os
construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument(“-d”, “–dataset”, required=True,
help=“path to input dataset”)
ap.add_argument(“-m”, “–model”, type=str, required=True,
help=“path to trained model”)
ap.add_argument(“-l”, “–le”, type=str, required=True,
help=“path to label encoder”)
ap.add_argument(“-p”, “–plot”, type=str, default=“plot.png”,
help=“path to output loss/accuracy plot”)
args = vars(ap.parse_args())
我们的面部活力训练脚本由许多导入(第 2-19 行)组成。现在让我们回顾一下:
-
matplotlib :用于生成训练图。我们指定了“Agg”后端,以便我们可以轻松地将我们的绘图保存到第 3 行的磁盘中。
-
LivenessNet :我们在上一节中定义的 liveness CNN。
-
train_test_split :来自 scikit-learn 的一个函数,它构建了我们的数据分割以进行训练和测试。 分类报告:同样来自 scikit-learn,该工具将生成关于我们模型性能的简要统计报告。
-
ImageDataGenerator :用于执行数据增强,为我们提供批量随机变异的图像。
-
Adam :一个非常适合这个模型的优化器。 (替代方法包括 SGD、RMSprop 等)。 路径:从我的 imutils 包中,该模块将帮助我们收集磁盘上所有图像文件的路径。
-
pyplot :用于生成一个很好的训练图。
-
numpy :Python 的数值处理库。这也是 OpenCV 的要求。
-
argparse :用于处理命令行参数。
-
pickle :用于将我们的标签编码器序列化到磁盘。
-
cv2 :我们的 OpenCV 绑定。
-
os :这个模块可以做很多事情,但我们只是将它用作操作系统路径分隔符。
查看脚本的其余部分应该更简单。 此脚本接受四个命令行参数:
-
–dataset :输入数据集的路径。 在这篇文章的前面,我们使用 gather_examples.py 脚本创建了数据集。
-
–model :我们的脚本将生成一个输出模型文件——在这里你提供它的路径。
-
–le :还需要提供输出序列化标签编码器文件的路径。
-
–plot :训练脚本将生成一个绘图。 如果你想覆盖 “plot.png” 的默认值,你应该在命令行中指定这个值。
下一个代码块将执行一些初始化并构建我们的数据:
initialize the initial learning rate, batch size, and number of
epochs to train for
INIT_LR = 1e-4
BS = 8
EPOCHS = 50
grab the list of images in our dataset directory, then initialize
the list of data (i.e., images) and class images
print(“[INFO] loading images…”)
imagePaths = list(paths.list_images(args[“dataset”]))
data = []
labels = []
loop over all image paths
for imagePath in imagePaths:
extract the class label from the filename, load the image and
resize it to be a fixed 32x32 pixels, ignoring aspect ratio
label = imagePath.split(os.path.sep)[-2]
image = cv2.imread(imagePath)
image = cv2.resize(image, (32, 32))
update the data and labels lists, respectively
data.append(image)
labels.append(label)
convert the data into a NumPy array, then preprocess it by scaling
all pixel intensities to the range [0, 1]
data = np.array(data, dtype=“float”) / 255.0<