翼度科技»论坛 编程开发 python 查看内容

使用python AI快速比对两张人脸图像及遇到的坑

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
本篇文章的代码块的实现主要是为了能够快速的通过python第三方非标准库对比出两张人脸是否一样。
实现过程比较简单,但是第三方python依赖的安装过程较为曲折,下面是通过实践对比总结出来的能够支持的几个版本,避免大家踩坑。
  1. python版本:3.6.8
  2. dlib版本:19.7.0
  3. face-recognition版本:0.1.10
复制代码
开始之前,我们选择使用pip的方式对第三方的非标准库进行安装。
  1. pip install cmake

  2. pip install dlib==19.7.0

  3. pip install face-recognition==0.1.10

  4. pip install opencv-python
复制代码
然后,将使用到的模块cv2/face-recognition两个模块导入到代码块中即可。
  1. # OpenCV is a library of programming functions mainly aimed at real-time computer vision.
  2. import cv2

  3. # It's loading a pre-trained model that can detect faces in images.
  4. import face_recognition
复制代码
新建一个python函数get_face_encodings,用来获取人脸部分的编码,后面可以根据这个编码来进行人脸比对。
  1. def get_face_encodings(image_path):
  2.     """
  3.     It takes an image path, loads the image, finds the faces in the image, and returns the 128-d face encodings for each
  4.     face

  5.     :param image_path: The path to the image to be processed
  6.     """
  7.     # It's loading a pre-trained model that can detect faces in images.
  8.     image = cv2.imread(image_path)

  9.     # It's converting the image from BGR to RGB.
  10.     image_RGB = image[:, :, ::-1]

  11.     image_face = face_recognition.face_locations(image_RGB)

  12.     # It's taking the image and the face locations and returning the face encodings.
  13.     face_env = face_recognition.face_encodings(image_RGB, image_face)

  14.     # It's returning the first face encoding in the list.
  15.     return face_env[0]
复制代码
上述函数中注释都是通过Pycharm插件自动生成的,接下来我们直接调用get_face_encodings函数分别获取两个人脸的编码。
  1. # It's taking the image and the face locations and returning the face encodings.
  2. ima1 = get_face_encodings('03.jpg')

  3. # It's taking the image and the face locations and returning the face encodings.
  4. ima2 = get_face_encodings('05.jpg')

  5. # It's taking the image and the face locations and returning the face encodings.
  6. ima1 = get_face_encodings('03.jpg')

  7. # It's taking the image and the face locations and returning the face encodings.
  8. ima2 = get_face_encodings('05.jpg')
复制代码
上面我们选择了两张附有人脸的图片,并且已经获取到了对应的人脸编码。接着使用compare_faces函数进行人脸比对。
  1. # It's comparing the two face encodings and returning True if they match.
  2. is_same = face_recognition.compare_faces([ima1], ima2, tolerance=0.3)[0]

  3. print('人脸比对结果:{}'.format(is_same))
复制代码
人脸比对结果:False
这个时候人脸比对结果已经出来了,False代表不一样。这里compare_faces有一个比较重要的参数就是tolerance=0.3,默认情况下是0.6。
tolerance参数的值越小的时候代表比对要求更加严格,因此这个参数的大小需要根据实际情况设置,它会直接影响整个比对过程的结果。
到此这篇关于如何使用python AI快速比对两张人脸图像?的文章就介绍到这了,更多相关python AI快速比对两张人脸图像内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/276290.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具