人脸识别正在成为软件开发中的一种趋势。它有助于识别人脸并使应用程序更加健壮。在本教程中,我们将使用pythonface_recognition库创建一个简单的人脸识别。
对于开发环境,我们将使用 Visual Studio Community Edition。
如果你的计算机上还没有安装它,你可以从这里下载:https://visualstudio.microsoft.com/downloads/。并使用 C++安装桌面开发。
现在我们有了使用 C++ 进行桌面开发的 Visual Studio,我们可以开始我们的项目了。
使用 Visual Studio 打开一个新目录并创建一个新的 python 环境。我们将使用venv. 打开你的集成终端并编写python -m venv venv。然后通过键入venv/bin/Activate.ps1激活环境。这是针对 PowerShell 的。
如果你使用任何其他终端,你可以在此处找到完整列表:https://docs.python.org/3/library/venv.html
现在我们已经完成了虚拟环境的创建,让我们开始提取我们的依赖项。为此,我们将需要opencvface_recognition。在你的终端内使用pip.
pip install opencv-python face_recognition

Face Recognition是一个使用最先进的dlib库的库。我们准备好编写一些代码并识别一些面孔。
创建一个新的 python 文件,我们将调用文件missingPerson.py,假设我们将使用我们的应用程序匹配失踪人员。导入我们的依赖项并编写我们的前几行。
import
 cv2

import
 numpy 
as
 np

import
 face_recognition

import
 os


from
 face_recognition.api 
import
 face_distance

假设我们所有的照片都存储在我们的服务器存储中,我们需要首先将所有人物的图像拉入我们的应用程序并读取这些图像。
path = 
'MissingPersons'
images = []

missingPersons = []

missingPersonsList = os.listdir(path)


for
 missingPerson 
in
 missingPersonsList :

    curImg = cv2.imread(
f'{path}/{missingPerson}'
)

    images.append(curImg)

    missingPersons.append(os.path.splitext(missingPerson)[
0
])

print(missingPersons)

在本节中,我们将使用 opencv 读取失踪人员的所有图像并将它们附加到我们的missingPerson列表中。
在我们从存储中读取所有丢失的人脸图像后,我们需要找到人脸编码,以便我们可以使用 CNN 人脸检测器在图像中创建人脸边界框的二维数组。
deffindEncodings(images):
    encodeList = []

for
 img 
in
 images:

        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        encode = face_recognition.face_encodings(img)[
0
]

        encodeList.append(encode)

    print(encodeList)

return
 encodeList


encodeListKnown = findEncodings(images)

print(
'Encoding Complete'
)

我们将二维数组存储到已知人脸编码列表中。这将需要几分钟。
现在我们有了所有失踪人员的面部编码,我们现在要做的就是将它们与我们的报告人图像进行匹配。face_recognition使用起来非常方便。
deffindMissingPerson(encodeListKnown, reportedPerson='found1.jpg'):
    person = face_recognition.load_image_file(
f'ReportedPersons/{reportedPerson}]'
)

    person = cv2.cvtColor(person,cv2.COLOR_BGR2RGB)


try
:

        encodePerson = face_recognition.face_encodings(person)[
0
]


        comparedFace = face_recognition.compare_faces(encodeListKnown,encodePerson)

        faceDis = face_recognition.face_distance(encodeListKnown,encodePerson)

        matchIndex = np.argmin(faceDis)

if
 comparedFace[matchIndex]:

            name = missingPersons[matchIndex].upper()

            print(name)

return
 name

else
:

          print(
'Not Found'
)

returnFalse

except
 IndexError 
as
 e:

        print(e)

return
 e

首先我们需要加载被报告人的图像文件,对他们的脸进行编码。剩下的就是将被报告人脸编码与我们已知的人脸编码进行比较。然后一个简单的逻辑匹配他们的索引并返回是否在我们的 missingPersons 列表中找到该人。
这种人脸识别不仅用于寻找失踪人员。它可以检测和识别人脸,并且可以根据需要进行操作。
☆ END ☆
如果看到这里,说明你喜欢这篇文章,请转发、点赞。微信搜索「uncle_pn」,欢迎添加小编微信「 woshicver」,每日朋友圈更新一篇高质量博文
扫描二维码添加小编↓
继续阅读
阅读原文