目录

相关包的安装

基于OpenCV的人脸识别

基于face_recognition算法的人脸识别

HOG(默认)

CNN 


相关包的安装

需要下载的扩展包:opencv-python以及face-recognition

!pip install opencv-python
!pip install face-recognition

导入/安装相关包(先安装完成这些包才能安装扩展包)

import cv2
import os
import matplotlib.pyplot as plt
!pip install CMake
!pip install scipy
!pip install -U scikit-image
!pip install dlib

注意⚠️ 

先安装CMake,scipy,-U scikit-image,才能安装dlib,安装dlib之后,才能安装face_recognition

不安装好-U scikit-image的话,会报错error: failed building wheel for dlib(虽然我也不知道这个包和wheel有什么关系,但是装完就好了)

基于OpenCV的人脸识别

os.chdir('/Users/mac/opt/anaconda3/lib/python3.8/site-packages/cv2/data')

定位到cv2所在文件的位置

def detect(filename):
    face_cascade=cv2.CascadeClassifier('/Users/mac/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    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('xh.JPG')

 

 

基于face_recognition算法的人脸识别

HOG(默认)

image = face_recognition.load_image_file("withp.jpg")
face_locations=face_recognition.face_locations(image)
face_num2=len(face_locations)
print(face_num2)  
org = cv2.imread("withp.jpg")
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,255)
    thickness = 2
    img=cv2.rectangle(org, start, end, color, thickness)
    plt.imshow(img)
    plt.axis('off')  
plt.show()

 

 

 

可以通过调整color等参数调节方框的颜色和粗细

CNN 

CNN模式准确度较高,但运算较慢(所以我自己的结果并没有得到)

face_locations_useCNN = face_recognition.face_locations(image,model='cnn')
face_num1=len(face_locations_useCNN)
print(face_num1)      
org = cv2.imread("wxy.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,255)
    thickness = 2
    img=cv2.rectangle(org, start, end, color, thickness)  
    plt.imshow(img)
    plt.axis('off') 
plt.show()

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐