"Dlib 是一个现代化的 C ++ 工具包, 包含用于创建复杂软件的机器学习算法和工具". 它使您能够直接在 Python 中运行许多任务, 其中一个例子就是人脸检测.
"Dlib 是一个现代化的 C ++ 工具包, 包含用于创建复杂软件的机器学习算法和工具". 它使您能够直接在 Python 中运行许多任务, 其中一个例子就是人脸检测.
安装 dlib 并不像只做一个 "pip install dlib" 那么简单, 因为要正确配置和编译 dlib, 您首先需要安装其他系统依赖项. 如果你按照这里描述的步骤, 它应该很容易让 dlib 启动并运行.(在本文中, 我将介绍如何在 Mac 上安装 dlib, 但如果您使用的是 Ubuntu, 请务必查看相关资源部分的链接.)
你需要确定的第一件事是你已经安装和更新了 Hombrew. 如果您需要安装它, 请将其粘贴到终端中:
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
或者, 如果您需要更新 Hombrew, 请输入以下内容:
$ brew update
您现在可以使用 Homebrew 来安装 CMake,Boost.Python, 以及在您的系统中正确配置和编译 dlib 所需的两个依赖关系:
$ brew install cmake
$ brew install boost-python
最后, 您需要手动下载并安装 XQuartz.
您现在已准备好安装 dlib. 我们将通过首先为这个项目创建一个孤立的虚拟环境来做到这一点. 我将使用 virtualenv, 但您可以使用任何您熟悉的虚拟环境工具, 包括 Python 的 venv 模块. 需要 scikit-image 库才能读取我们稍后将传递给 dlib 的图像文件, 因此我们还需要 pip 安装它:
- $ virtualenv venv_dlib
- $ source venv_dlib / bin / activate
$ pip install scikit-image
$ pip install dlib
就是这样. 有了这个, 你应该有可用的 dlib.
Dlib
Dlib 提供了不同的脸部检测算法. 我将在这里使用的是基于 CNN 的人脸检测器. 您可以下载预训练模型: https://github.com/davisking/dlib-models. 由于使用此模型的计算成本很高, 因此最好在 GPU 上执行以下代码. 使用 CPU 也可以, 但速度会更慢.
要在下面的要点中运行人脸检测代码, 我建议首先在虚拟环境中再安装两个库. 这些库将使与代码交互和可视化结果更容易:
$ pip install matplotlib
$ pip install jupyterlab
安装完库后, 您需要确保:
下载预训练模型 (http://dlib.net/files/mmod_human_face_detector.dat.bz2) 并将其存储在项目的根目录中
创建一个名为'faces'的新目录, 在该目录中存储带有希望检测的脸部的. jpg.
有了这个, 你终于准备好开始在图片中检测脸部了! 您可以通过在 Jupyter Notebook 中运行以下代码来完成此操作
- import dlib
- import matplotlib.patches as patches
- import matplotlib.pyplot as plt
- from pathlib import Path
- from skimage import io
- %matplotlib inline
- # Load trained model
cnn_face_detector = dlib.cnn_face_detection_model_v1(
- 'mmod_human_face_detector.dat')
- # Function to detect and show faces in images
- def detect_face_dlib(img_path, ax):
- # Read image and run algorithm
- img = io.imread(img_path)
- dets = cnn_face_detector(img, 1)
- # If there were faces detected, show them
- if len(dets) > 0:
- for d in dets:
- rect = patches.Rectangle(
- (d.rect.left(), d.rect.top()),
- d.rect.width(),
- d.rect.height(),
- fill=False,
- color='b',
- lw='2')
- ax.add_patch(rect)
- ax.imshow(img)
- ax.set_title(str(img_path).split('/')[-1])
- # Path to images
- images = list(Path('faces').glob('*.jpg'))
- # Show results
- fig = plt.figure(figsize=(15, 5))
- for i, img in enumerate(images):
- ax = fig.add_subplot(1, len(images), i+1)
- detect_face_dlib(img, ax)
结果
在运行代码之后, 您应该看到图像中的脸部周围出现蓝色方块, 如果您问我, 考虑到我们只写了几行代码, 这非常棒!
来源: http://developer.51cto.com/art/201805/572862.htm