lesson2:人脸识别

常用

  1. 查看当前路径 import os print(os.getcwd())
    2.python安装包的路径: C:\Users\kong\AppData\Local\Programs\Python\Python38\Lib\site-packages

一、opencv识别人脸

import cv2
import os
import matplotlib.pyplot as plt 
# print(os.getcwd()) 查看当前目录
def detect(filepath):
    face_cascade = cv2.CascadeClassifier(r'C:\Users\kong\AppData\Local\Programs\Python\Python38\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
    #face_cascade = cv2.CascadeClassifier(r'C:\Users\kong\AppData\Local\Programs\Python\Python38\Lib\site-packages\cv2\data\haarcascade_lefteye_2splits.xml')
    img = cv2.imread(filepath)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    faces = face_cascade.detectMultiScale(gray,1.3,5)
    # detectMultiScale函数作用进行多尺度目标检测;返回特征参数列表
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x + w, y + h),(255, 0, 0),2)       
    plt.imshow(img)
    plt.axis('off')
    plt.show()

detect('pic/tong.jpg')
opencv实现人脸识别.png

补充

  • 使用库:cv2 (定位;对齐;识别)
  • BUG:
    1. 注意缩进 - IndentationError: expected an indented block
    2. 路径:windows系统中用 " \ "读取文件路径,但python中有转义的含义。
      解决方案:在路径前加 r ;替换为" \ "或"/"
  • detectMultiScale函数[1]

二、face-recognition

HOG算法

默认使用HOG算法

import face_recognition
import cv2
import matplotlib.pyplot as plt
'''
PIL.Image.open打开图片
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
'''
#识别图片中人数
image = face_recognition.load_image_file('pic/5.jpg')
face_locations=face_recognition.face_locations(image)
face_num2=len(face_locations)
print(face_num2)
print(face_locations)

#方框标记
org=cv2.imread('pic/5.jpg') 
'''
显示原图色彩
image=Image.open('pic/5.jpg')
org=np.array(image) 
'''
for i in range(0,face_num2):
    top=face_locations[i][0]
    right=face_locations[i][1]
    bottom=face_locations[i][2]
    left=face_locations[i][3]
    
    start=(left,top)
    end=(right,bottom)
    color=(0,255,0)
    thickness=2
    img=cv2.rectangle(org,start,end,color,thickness)
plt.imshow(img)
plt.axis('off')
plt.show()

补充
1.所用库:face-recognition
face-recognition依赖于Dlib,Dlib依赖于OpenCV
安装dlib问题
python3.8编译好的轮子:https://blog.csdn.net/i__wonder/article/details/110638578

  1. 基础信息:
    whl文件地址:https://pypi.org/
    查资料的文档:win→python3.8→python3.8 module docs
  2. 读图
    PIL.Image.open读入的是RGB顺序,而opencv中cv2.imread读入的是BGR通道顺序 。cv2.imread会显示图片更蓝一些。


    不同读图方式对比.png
  • cv2.imread(path,读取方式)方法
    读取方法有:
    cv2.IMREAD_COLOR:加载彩色图片,这个是默认参数,可以直接写1。
    cv2.IMREAD_GRAYSCALE:以灰度模式加载图片,可以直接写0。
    cv2.IMREAD_UNCHANGED:包括alpha,可以直接写-1

  • PIL.Image.open(path)方法
    需要用img=np.array(img)做转换,才能看到shape属性[2]

CNN

准确率更高;更慢

# CNN卷积神经网络
import face_recognition
import cv2
import matplotlib.pyplot as plt

image = face_recognition.load_image_file("pic/all.jpg")
face_locations_useCNN = face_recognition.face_locations(image,model='cnn')

face_num1=len(face_locations_useCNN)
print(face_num1)   # The number of faces
org=cv2.imread("pic/all.jpg")

for i in range(0,face_num1):
    top=face_locations_useCNN[i][0]
    right=face_locations_useCNN[i][1]
    bottom=face_locations_useCNN[i][2]
    left=face_locations_useCNN[i][3]
    
    start=(left,top)
    end=(right,bottom)
    color=(0,255,0)
    thickness=2
    img=cv2.rectangle(org,start,end,color,thickness)   #opencv里面画矩形的函数
plt.imshow(img)
plt.axis('off')
plt.show()
# 依然有一个侧脸没有识别到
CNN识别.png

三、人脸对齐

定位点

import cv2
import dlib
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
'''
path = "pic/5.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
'''
imagePath='pic/5.jpg'
img=Image.open(imagePath)
img=np.array(img) 

#人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
#predictor = dlib.shape_predictor(r"C:\Users\kong\AppData\Local\Programs\Python\Python38\Lib\site-packages\face_recognition_models\models\shape_predictor_68_face_landmarks.dat")
predictor = dlib.shape_predictor(r"C:\Users\kong\AppData\Local\Programs\Python\Python38\Lib\site-packages\face_recognition_models\models\shape_predictor_5_face_landmarks.dat")

dets = detector(img, 1)
for face in dets:
    shape = predictor(img, face)  # 寻找人脸的68个标定点
    # 遍历所有点,打印出其坐标,并圈出来
    for pt in shape.parts():
        pt_pos = (pt.x, pt.y)
        img=cv2.circle(img, pt_pos, 5, (0,255,0), 1)

#print(img.shape)
plt.imshow(img)
plt.axis('off')
plt.show()

由于定位点不明显换用了彩色照片


68个定位点&5个定位点.png
  • 探索人工智能第五集 https://www.iqiyi.com/v_19rr7hc8sg.html
  • 人脸识别
  • 视频捕获中的人脸定位

三、人脸比对

import cv2
import face_recognition
import matplotlib.pyplot as plt

known_image=cv2.imread('pic/5.jpg')
known_image=face_recognition.load_image_file('pic/5.jpg')

unknown_image=cv2.imread('pic/nini.jpg')
unknown_image=face_recognition.load_image_file('pic/nini.jpg')

known_encoding=face_recognition.face_encodings(known_image)[0]
unknown_encoding= face_recognition.face_encodings(unknown_image)[0]

results = face_recognition.compare_faces([known_encoding],
                                        unknown_encoding,
                                        tolerance=0.5)
if results[0]==True:
    print('匹配成功,该未知图片与已有图片人脸可匹配')
else:
    print('匹配失败!')
#print(known_encoding)
#print(unknown_encoding)
plt.imshow(known_image)
plt.axis('off')
plt.show()

plt.imshow(unknown_image)
plt.axis('off')
plt.show()
比对结果.png

过程中出现了识别错误(见上图箭头),通过减少tolerance完成了订正。但依然存在同一个人匹配不上的情况。


tolerance=0.3.png

  1. https://blog.csdn.net/weixin_42213622/article/details/108213708

  2. https://www.jb51.net/article/187938.htm

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容