Python face_recognition 库人脸识别/匹配教程

£神魔★判官ぃ 2023-10-02 11:24 42阅读 0赞

#

在本教程中,我将解释 Python face_recognition 库的设置和使用。该库可用于使用 Python 检测人脸并识别面部特征。


  • 目标
  • 安装“face_recognition”库
  • 检测图像中的人脸
  • 检测图像中的多张人脸
  • 识别面部特征
  • 匹配检测到的人脸
  • 其他 PIL 帮助

目标

在本教程中,我将介绍 Python face_recognition 库的一些示例用法:

  • 检测图像中的人脸
  • 在检测到的脸上检测面部特征(如眉毛和鼻子)
  • 检查检测到的人脸是否匹配

这篇文章提供了所有图像和代码片段,以及有关正在发生的事情的分步说明和解释。本教程针对 Windows 10,但 Linux 和 macOS 用户很可能会发现这更容易,因为他们可以跳过一些先决条件。

如果您需要/想要它们,以下是 face_recognition 的一些相关链接:

  • 文档:face-recognition.readthedocs.io
  • 源代码:github.com/ageitgey/face_recognition
  • PyPI:pypi.org/project/face-recognition

安装“face_recognition”库

先决条件 (Windows)

要在 Windows 上安装 face_recognition 库,您需要安装以下内容:

  • 制作
  • Visual Studio C++ 构建工具

如果你没有这些,你会得到这样的错误,

  1. CMake must be installed to build the following extensions: _dlib_pybind11

这告诉你没有安装 CMake,或者,

  1. You must use Visual Studio to build a python extension on windows. If you
  2. are getting this error it means you have not installed Visual C++. Note
  3. that there are many flavours of Visual Studio, like Visual Studio for C#
  4. development. You need to install Visual Studio for C++.

这告诉您您需要 Visual Studio C++ 构建工具。

制作

要安装 CMake,请转到cmake.org/download/并下载适合您机器的安装程序。我使用的是 64 位 Windows 10,所以我会得到cmake-<version>-win64-x64.msi. 下载安装文件后,安装它。

在安装 CMake 时,将 CMake 添加到所有用户或当前用户的系统 PATH 环境变量中,以便轻松找到它。

安装完成后,打开终端并执行cmake。这应该显示 CMake 的用法。如果没有,请确保您选择了将其添加到 PATH 环境变量的选项。

您需要关闭并重新打开终端/应用程序以更新 PATH 变量,以便cmake识别二进制文件。

Visual Studio C++ 构建工具

与 Linux 不同,操作系统中默认不包含适用于 Windows 的 C++ 编译器。如果我们访问 Python wiki 上的 WindowsCompilers 页面,我们可以看到有关获取独立版本的 Visual C++ 14.2 编译器而无需 Visual Studio 的信息。如果我们访问该wiki 部分的链接,我们将被带到 Microsoft 下载页面。在此下载页面上,您需要下载“Visual Studio 2019 的构建工具”。

vs_buildtools__<some other stuff>.exe下载完成,运行exe并允许它之前,我们得到下面的屏幕安装的几件事情。当您到达此屏幕时,请进行我的选择:

单击“安装”后,等待安装完成并重新启动。

现在安装了 CMake 和所需的构建工具,我们可以继续安装 face_recognition 库。

安装 face_recognition 并验证安装

要安装 face_recognition 库,请在终端中执行以下操作:

  1. python -m pip install face-recognition

这可能需要比平时更长的时间来安装,因为 dlib 需要使用从上面安装的工具来构建。要验证库是否已成功安装,请尝试使用以下命令在 Python 中导入库:

  1. import face_recognition

不应引发任何错误。

安装 PIL

在本教程中,我们还将使用Pillow / PIL 来帮助我们裁剪和绘制图像。这不是使用 face_recognition 库所必需的,但在本教程中需要以证明/显示结果。要安装它,请执行以下操作:

  1. python -m pip install Pillow

要验证库是否已安装,请尝试使用以下命令在 Python 中导入 PIL:

  1. import PIL

不应引发任何错误。

检测图像中的人脸

现在我们已经设置了 face_recognition 库和 PIL,我们现在可以开始检测人脸了。首先,我们将在只有一个人的图像中检测人脸。

单人.jpg

首先,我们要从 PIL 导入 face_recognition 和一些助手。

  1. import face_recognition
  2. from PIL import Image, ImageDraw

现在使用face_recognition.load_image_file.

  1. image = face_recognition.load_image_file('single-person.jpg')

image现在以 face_recognition 可以检测人脸的格式包含我们的图像。要识别此图像中人脸的位置,请调用face_recognition.face_locations并传递图像。

  1. face_locations = face_recognition.face_locations(image)

face_locations现在将包含面部位置列表。每个人脸位置都是一个像素位置元组(top, right, bottom, left)- 我们需要记住这一点,以便我们以后使用它。

由于此图像中只有一张脸,因此我们希望此列表中只有一个项目。要检查检测到多少人脸,我们可以获取列表的长度。

  1. amount = len(face_locations)
  2. print(f'There are { amount} face locations')

对于我在上面提供并用于本教程的示例图像,这告诉我检测到一张脸。

为了以后使用这个面的位置,我们可以只从列表中取出第一个元素。

  1. first_face_location = face_locations[0]

要查看其中的内容,您可以调用:

  1. print(first_face_location)

这将打印出如下内容:

  1. (400, 1221, 862, 759)

这些是(top, right, bottom, left)我们将用于创建框和裁剪的像素位置。

识别检测到的人脸

为了识别图像中检测到的人脸的位置,我们将在由 返回的边界上绘制一个红色框face_recognition.face_locations

首先,我们需要从使用加载的图像创建一个 PIL 图像face_recognition.load_image_file。这样做将允许我们使用 PIL 提供的功能。

  1. img = Image.fromarray(image, 'RGB')

现在我们有了 PIL 图像,我们需要创建一个对象来帮助我们在图像上绘制。在我们这样做之前,我们还将把图像复制到一个新对象中,这样当我们以后裁剪脸部时,它周围就不会再有一个红色框了。

  1. img_with_red_box = img.copy()
  2. img_with_red_box_draw = ImageDraw.Draw(img_with_red_box)

现在我们有一个对象可以帮助我们在图像上绘制,我们将使用之前返回的尺寸绘制一个矩形。

要绘制一个框,我们需要两个点,左上角和右下角作为 x 和 y 坐标。既然我们回来了(top, right, bottom, left),我们就需要做这些(left, top), (right, bottom);基本翻译如下。

  1. img_with_red_box_draw.rectangle(
  2. [
  3. (first_face_location[3], first_face_location[0]),
  4. (first_face_location[1], first_face_location[2])
  5. ],
  6. outline="red",
  7. width=3
  8. )

我们需要(left, top), (right, bottom)得到 (x, y) (x, y) 点。

在该步骤中,我们还设置outline="red"了使框为红色width=3并使框为 3 像素宽。

要查看最终结果,我们调用:

  1. img_with_red_box.show()

这将在默认图像查看器中打开图像。图像应如下所示:

裁剪出检测到的人脸

除了绘制一个框外,我们还可以将人脸裁剪成另一幅图像。

使用我们没有绘制的原始图像(因为我们在复制的图像上绘制),我们可以调用img.crop提供之前的尺寸。

  1. img_cropped = img.crop((
  2. first_face_location[3], # Left x
  3. first_face_location[0], # Top y
  4. first_face_location[1], # Right x
  5. first_face_location[2] # Bottom y
  6. ))

img.crop 返回正在复制的原始图像的副本,因此如果您想对原始图像执行其他操作,则无需事先复制。

img_cropped现在包含一个新的裁剪图像,要显示它,我们可以.show()再次调用。

  1. img_cropped.show()

本节的最终代码

  1. import face_recognition
  2. from PIL import Image, ImageDraw
  3. # Detecting the faces
  4. image = face_recognition.load_image_file('single-person.jpg') # Load the image
  5. face_locations = face_recognition.face_locations(image) # Detect the face locations
  6. first_face_location = face_locations[0] # Get the first face
  7. # Convert the face_recognition image to a PIL image
  8. img = Image.fromarray(image, 'RGB')
  9. # Creating the image with red box
  10. img_with_red_box = img.copy() # Create a copy of the original image so there is not red box in the cropped image later
  11. img_with_red_box_draw = ImageDraw.Draw(img_with_red_box) # Create an image to draw with
  12. img_with_red_box_draw.rectangle( # Draw the rectangle on the image
  13. [
  14. (first_face_location[3], first_face_location[0]), # (left, top)
  15. (first_face_location[1], first_face_location[2]) # (right, bottom)
  16. ],
  17. outline="red", # Make the box red
  18. width=3 # Make the box 3px in thickness
  19. )
  20. img_with_red_box.show() # Open the image in the default image viewer
  21. # Creating the cropped image
  22. img_cropped = img.crop(( # Crop the original image
  23. first_face_location[3],
  24. first_face_location[0],
  25. first_face_location[1],
  26. first_face_location[2]
  27. ))
  28. img_cropped.show() # Open the image in the default image viewer

检测图像中的多张人脸

我们之前看到它face_recognition.face_locations返回一个与人脸位置对应的元组数组。这意味着我们可以使用与上面相同的方法,但循环face_recognition.face_locations绘制和裁剪时的结果。

我将使用以下作为我的形象。它有 5 个可见的面,其中 2 个略微模糊。

一群人.jpg

再一次,我们想从 PIL 导入 face_recognition 和一些助手。

  1. import face_recognition
  2. from PIL import Image, ImageDraw

然后使用face_recognition.load_image_file与以前相同的方法加载新图像并检测人脸。

  1. image = face_recognition.load_image_file('group-of-people.jpg')
  2. face_locations = face_recognition.face_locations(image)

如果我们打印出face_locations( print(face_locations)),我们可以看到已经检测到了5张脸。

  1. [
  2. (511, 1096, 666, 941),
  3. (526, 368, 655, 239)
  4. (283, 1262, 390, 1154),
  5. (168, 1744, 297, 1615),
  6. (271, 390, 378, 282)
  7. ]

由于我们现在有多个面,取第一个没有意义——我们应该遍历它们并在循环中执行我们的操作。

在我们继续之前,我们还应该创建我们将使用的 PIL 图像。

  1. img = Image.fromarray(image, 'RGB')

识别检测到的人脸

像以前一样,我们需要复制原始图像以备后用(可选)并创建一个对象来帮助我们绘制。

  1. img_with_red_box = img.copy()
  2. img_with_red_box_draw = ImageDraw.Draw(img_with_red_box)

现在我们可以循环所有面并创建矩形。

  1. for face_location in face_locations:
  2. img_with_red_box_draw.rectangle(
  3. [
  4. (face_location[3], face_location[0]),
  5. (face_location[1], face_location[2])
  6. ],
  7. outline="red",
  8. width=3
  9. )

再一次,看看图像:

  1. img_with_red_box.show()

不错诶!

裁剪检测到的人脸

就像绘制许多框一样,我们也可以裁剪所有检测到的人脸。再次使用 for 循环,在每个循环中裁剪图像,然后显示图像。

  1. for face_location in face_locations:
  2. img_cropped = img.crop((face_location[3], face_location[0], face_location[1], face_location[2]))
  3. img_cropped.show()

您将在您的机器上在单独的窗口中打开许多图像;在这里,他们都在一起:

一群人裁剪的脸 2

一群人裁剪的脸 3

一群人裁剪的脸 4

一群人裁剪的脸 5

我已经为教程缩小了这些图像的尺寸,但您的图像将以您输入的任何分辨率进行裁剪。

本节的最终代码

  1. import face_recognition
  2. from PIL import Image, ImageDraw
  3. # Load image and detect faces
  4. image = face_recognition.load_image_file("group-of-people.jpg")
  5. face_locations = face_recognition.face_locations(image)
  6. # Create the PIL image to copy and crop
  7. img = Image.fromarray(image, 'RGB')
  8. img_with_red_box = img.copy() # Make a single copy for all the red boxes
  9. img_with_red_box_draw = ImageDraw.Draw(img_with_red_box) # Get our drawing object again
  10. for face_location in face_locations: # Loop over all the faces detected this time
  11. img_with_red_box_draw.rectangle( # Draw a rectangle for the current face
  12. [
  13. (face_location[3], face_location[0]),
  14. (face_location[1], face_location[2])
  15. ],
  16. outline="red",
  17. width=3
  18. )
  19. img_with_red_box.show() # Open the image in the default image viewer
  20. for face_location in face_locations: # Loop over all the faces detected
  21. img_cropped = img.crop(( # Crop the current image like we did last time
  22. face_location[3],
  23. face_location[0],
  24. face_location[1],
  25. face_location[2]
  26. ))
  27. img_cropped.show() # Show the image for the current iteration

识别面部特征

face_recognition 也有一个函数face_recognition.face_landmarks,它的工作原理类似,face_recognition.face_locations但会返回一个包含人脸特征位置的字典列表,而不是检测到的人脸本身的位置。

回到只有一个人的图像,我们可以再次导入所有内容,加载图像并调用face_recognition.face_landmarks.

  1. import face_recognition
  2. from PIL import Image, ImageDraw
  3. image = face_recognition.load_image_file('single-person.jpg')
  4. face_landmarks_list = face_recognition.face_landmarks(image) # The new call

现在如果我们打印face_landmarks_list,对象看起来会有点不同。

  1. [
  2. {
  3. 'chin': [(315, 223), (318, 248), (321, 273), (326, 296), (335, 319), (350, 339), (370, 354), (392, 365), (415, 367), (436, 363), (455, 351), (469, 336), (479, 318), (486, 296), (488, 273), (490, 251), (489, 229)],
  4. 'left_eyebrow': [(329, 194), (341, 183), (358, 180), (375, 182), (391, 189)],
  5. 'right_eyebrow': [(434, 189), (448, 184), (461, 182), (474, 184), (483, 194)],
  6. 'nose_bridge': [(411, 209), (411, 223), (412, 238), (412, 253)],
  7. 'nose_tip': [(394, 269), (403, 272), (412, 275), (421, 272), (428, 269)],
  8. 'left_eye': [(349, 215), (360, 208), (373, 207), (384, 216), (372, 218), (359, 219)],
  9. 'right_eye': [(436, 216), (446, 208), (458, 208), (467, 216), (459, 219), (447, 219)],
  10. 'top_lip': [(374, 309), (388, 300), (402, 296), (411, 298), (420, 296), (434, 301), (448, 308), (442, 308), (420, 307), (411, 308), (402, 307), (380, 309)],
  11. 'bottom_lip': [(448, 308), (434, 317), (421, 321), (411, 322), (401, 321), (388, 317), (374, 309), (380, 309), (402, 309), (411, 310), (421, 309), (442, 308)]
  12. }
  13. ]

这里有很多东西。对于每个面部特征(即下巴、左眉、右眉等),相应的列表包含 x 和 y 元组 - 这些 x 和 y 点是图像上的 x 和 y 坐标。

PIL 为.line()我们一直使用的绘图对象提供了一种方法,它采用 x 和 y 点列表,非常适合这种情况。首先,我们需要一个绘图对象。

  1. img = Image.fromarray(image, 'RGB') # Make a PIL image from the loaded image
  2. img_draw = ImageDraw.Draw(img) # Create the draw object

在这个例子中,我们不会复制图像,因为这是我们唯一一次使用它

现在我们有了帮助我们绘制的对象,使用上面返回的列表中的第一个字典绘制所有这些线。

  1. face_landmarks = face_landmarks_list[0] # Get the first dictionary of features
  2. img_draw.line(face_landmarks['chin'])
  3. img_draw.line(face_landmarks['left_eyebrow'])
  4. img_draw.line(face_landmarks['right_eyebrow'])
  5. img_draw.line(face_landmarks['nose_bridge'])
  6. img_draw.line(face_landmarks['nose_tip'])
  7. img_draw.line(face_landmarks['left_eye'])
  8. img_draw.line(face_landmarks['right_eye'])
  9. img_draw.line(face_landmarks['top_lip'])
  10. img_draw.line(face_landmarks['bottom_lip'])

现在我们可以调用.show()我们的图像来查看它:

  1. img_draw.show()

本节的最终代码

  1. import face_recognition
  2. from PIL import Image, ImageDraw
  3. # Load the image and detect face landmarks for each face within
  4. image = face_recognition.load_image_file('single-person.jpg')
  5. face_landmarks_list = face_recognition.face_landmarks(image)
  6. # Make a PIL image from the loaded image and then get a drawing object
  7. img = Image.fromarray(image, 'RGB')
  8. img_draw = ImageDraw.Draw(img)
  9. # Draw all the features for the first face
  10. face_landmarks = face_landmarks_list[0] # Get the first object corresponding to the first face
  11. img_draw.line(face_landmarks['chin'])
  12. img_draw.line(face_landmarks['left_eyebrow'])
  13. img_draw.line(face_landmarks['right_eyebrow'])
  14. img_draw.line(face_landmarks['nose_bridge'])
  15. img_draw.line(face_landmarks['nose_tip'])
  16. img_draw.line(face_landmarks['left_eye'])
  17. img_draw.line(face_landmarks['right_eye'])
  18. img_draw.line(face_landmarks['top_lip'])
  19. img_draw.line(face_landmarks['bottom_lip'])
  20. img_with_face_landmarks.show() # Show the image for the current iteration

匹配检测到的人脸

face_recognition 库还提供了face_recognition.compare_faces可用于比较检测到的人脸以查看它们是否匹配的功能。

我们将使用此函数的两个参数:

  • known_face_encodings:已知人脸编码列表
  • face_encoding_to_check:要与列表进行比较的单个人脸编码

在本节中,我们将为同一个人获取 2 个面部编码,并检查它们是否在另一张图像中。

以下是两张图片,每张图片中都有一张已知人脸:

elon-musk-1.jpg elon-musk-2.png

以下是我们将检查 Elon 是否在其中的图像:

elon-musk-in-group.jpg group-of-people.jpg

获取人脸编码

要获得已知的人脸编码,我们可以使用face_recognition.face_encodings. 此函数获取包含要使用的人脸和图像中人脸位置的图像。

通常,您只会使用一张图像中人脸的一个位置来创建一种编码,但如果您在一张图像中有多个相同的人脸,则可以提供多个位置。

我们需要做的来获得我们已知的人脸编码的过程是:

  1. 加载第一张图片
  2. 检测图像中的人脸以获取人脸位置
  3. 验证只有一个面并选择第一个面
  4. face_recognition.face_encodings使用图像和单人脸位置调用
  5. 对第二个图像重复 1 到 5

我们之前已经完成了步骤 1-3,所以我们可以在这里再次执行:

  1. import face_recognition
  2. # Load image and detect faces
  3. image = face_recognition.load_image_file("elon-musk-1.jpg")
  4. face_locations = face_recognition.face_locations(image)

并验证检测到一张脸:

  1. print(len(face_locations)) # Should be 1

现在我们可以调用face_recognition.face_encodings并提供图像和找到的位置。

  1. face_location = face_locations[0] # We only want an encoding for the first face. There may be more than one face in images you use so I am leaving this here as a note.
  2. face_encodings = face_recognition.face_encodings(image, [face_location])

该参数known_face_locations是可选的,如果known_face_locations未提供,face_recognition 将在获取人脸编码时自动检测图像中的所有人脸。对于这一部分,我将通过这种方式进行演示,以验证图像中仅检测到一张人脸。

由于我们指定了一个数组known_face_locations,我们知道将只返回一个编码,因此我们可以采用第一个。

  1. elon_musk_knwon_face_encoding_1 = face_encodings[0]

我们现在可以对另一个图像重复这个过程

  1. image = face_recognition.load_image_file("elon-musk-2.png") # Load the image
  2. face_locations = face_recognition.face_locations(image) # Get face locations
  3. face_location = face_locations[0] # Only use the first detected face
  4. face_encodings = face_recognition.face_encodings(image, [face_location]) # Get all face encodings
  5. elon_musk_knwon_face_encoding_2 = face_encodings[0] # Pull out the one returned face encoding

现在我们有了elon_musk_knwon_face_encoding_1elon_musk_knwon_face_encoding_2,我们可以看看它们是否存在于我们的另外两个图像中。

检查匹配

要检查图像中的匹配项face_recognition.compare_faces,我们需要已知的人脸编码(我们刚刚在上面获得)和要检查的单个人脸编码。

由于我们正在处理一组图像,我们将不得不循环检测到的人脸——尽管这也适用于图像中只有一个人的情况。

首先,我们需要从要比较的第一张图像中获取所有面部解码。我在上面已经注意到第二个参数 , known_face_locationstoface_recognition.face_encodings是可选的,省略它会自动检测图像中的所有面部并返回图像中每个面部的面部编码;这正是我们想要的,并将删除检测人脸的中间步骤。

  1. image = face_recognition.load_image_file("elon-musk-in-group.jpg") # Load the image we are comparing
  2. unknwon_face_encodings = face_recognition.face_encodings(image) # Get face encodings for everyone in the image

现在我们有了组图像中所有人脸的未知人脸编码,我们可以遍历它们并检查是否匹配:

  1. for unknwon_face_encoding in unknwon_face_encodings:
  2. matches = face_recognition.compare_faces(
  3. [elon_musk_knwon_face_encoding_1, elon_musk_knwon_face_encoding_2], # The known face encodings (can be only 1 - less is faster)
  4. unknwon_face_encoding # The single unknown face encoding
  5. )
  6. print(matches)

如果你运行这个,你会看到类似的东西:

  1. [True, True]
  2. [False, False]
  3. [False, False]
  4. [False, False]

每行是一个比较(存储在 中matches),每个布尔值对应一个已知的人脸编码以及它是否与未知的人脸编码匹配。

从上面的值,我们可以看到组图像中的第一个未知人脸与已知人脸编码都匹配,而其他三个未知人脸与任何一个编码都不匹配。使用多次面部编码可以让您计算出更好的概率,但会降低速度。

如果你在另一个图像上运行这个,一切都会返回 false。

本节的最终代码

  1. import face_recognition
  2. # Load elon-musk-1.jpg and detect faces
  3. image = face_recognition.load_image_file("elon-musk-1.jpg")
  4. face_locations = face_recognition.face_locations(image)
  5. # Get the single face encoding out of elon-musk-1.jpg
  6. face_location = face_locations[0] # Only use the first detected face
  7. face_encodings = face_recognition.face_encodings(image, [face_location])
  8. elon_musk_knwon_face_encoding_1 = face_encodings[0] # Pull out the one returned face encoding
  9. # Load elon-musk-2.jpg and detect faces
  10. image = face_recognition.load_image_file("elon-musk-2.png")
  11. face_locations = face_recognition.face_locations(image)
  12. # Get the single face encoding out of elon-musk-2.jpg
  13. face_location = face_locations[0]
  14. face_encodings = face_recognition.face_encodings(image, [face_location])
  15. elon_musk_knwon_face_encoding_2 = face_encodings[0]
  16. # Load the image with unknown to compare
  17. image = face_recognition.load_image_file("elon-musk-in-group.jpg") # Load the image we are comparing
  18. unknwon_face_encodings = face_recognition.face_encodings(image)
  19. # Loop over each unknwon face encoding to see if the face matches either known encodings
  20. print('Matches for elon-musk-in-group.jpg')
  21. for unknwon_face_encoding in unknwon_face_encodings:
  22. matches = face_recognition.compare_faces(
  23. [elon_musk_knwon_face_encoding_1, elon_musk_knwon_face_encoding_2], # The known face encodings (can be only 1 - less is faster)
  24. unknwon_face_encoding # The single unknown face encoding
  25. )
  26. print(matches)
  27. # Load the other image with unknown to compare
  28. image = face_recognition.load_image_file("group-of-people.jpg") # Load the image we are comparing
  29. unknwon_face_encodings = face_recognition.face_encodings(image)
  30. # Loop over each unknwon face encoding to see if the face matches either known encodings
  31. print('Matches for group-of-people.jpg')
  32. for unknwon_face_encoding in unknwon_face_encodings:
  33. matches = face_recognition.compare_faces(
  34. [elon_musk_knwon_face_encoding_1, elon_musk_knwon_face_encoding_2],
  35. unknwon_face_encoding
  36. )
  37. print(matches)

其他 PIL 帮助

本教程不关注 PIL,但您可能会发现有用的一个功能是img.save();这将保存一个文件。其用法的一个示例是img.save('my_image.png')将 PIL 图像保存到 my_image.png。

你可以在它的文档中找到更多关于 PIL 的信息,还有很多其他的在线帮助,因为它是一个非常古老的图书馆。

发表评论

表情:
评论列表 (有 0 条评论,42人围观)

还没有评论,来说两句吧...

相关阅读