关于#python#的问题:别人给的一个基于python的人脸识别系统我不会用,求大神教教我

别人给的一个基于python的人脸识别系统
我不会用,求大神教教我
链接:https://pan.baidu.com/s/1q0jaPRipNTJXNTNc0DosaA?pwd=1234
提取码:1234
--来自百度网盘超级会员V1的分享

以下答案由GPT-3.5大模型与博主波罗歌共同编写:
首先,你需要安装OpenCV的python包,可以使用以下命令进行安装:

pip install opencv-python

接着,你需要将下载的人脸识别系统解压缩,并运行face_recognition.py文件。你可以在控制台中使用以下命令:

python face_recognition.py

如果你想要修改代码或理解更多细节,可以打开face_recognition.py文件并查看代码。该代码使用人脸检测和特征提取技术进行人脸识别,并使用OpenCV进行图像处理和展示。

以下是face_recognition.py文件的代码:

import cv2
import numpy as np
import os

# Load HAAR face classifier
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load functions
def face_extractor(img):
    # Function detects faces and returns the cropped face
    # If no face detected, it returns the input image
    
    # Convert image to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # Detect face using HAAR classifier
    faces = face_classifier.detectMultiScale(gray, 1.3, 5)
    
    if faces is ():
        return None
    
    # Crop all faces found
    for (x,y,w,h) in faces:
        cropped_face = img[y:y+h, x:x+w]

    return cropped_face


# Initialize webcam
cap = cv2.VideoCapture(0)
count = 0

# Collect 100 samples of your face from webcam input
while True:

    ret, frame = cap.read()
    if face_extractor(frame) is not None:
        count += 1
        face = cv2.resize(face_extractor(frame), (200, 200))
        # Save file in specified directory with unique name
        file_name_path = 'faces/user' + str(count) + '.jpg'
        cv2.imwrite(file_name_path, face)

        # Put count on images and display live count
        cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
        cv2.imshow('Face Cropper', face)
        
    else:
        print("Face not found")
        pass

    if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key
        break
        
cap.release()
cv2.destroyAllWindows()      
print("Collecting Samples Complete")


# Train model using images
from os import listdir
from os.path import isfile, join
data_path = './faces/'
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))]

# Create arrays for training data and labels
Training_Data, Labels = [], []

# Open training images in our datapath
# Create Labels for each image
for i, files in enumerate(onlyfiles):
    image_path = data_path + onlyfiles[i]
    images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    Training_Data.append(np.asarray(images, dtype=np.uint8))
    Labels.append(i)

# Create a numpy array for both training data and labels
Labels = np.asarray(Labels, dtype=np.int32)

# Initialize facial recognizer
model = cv2.face.LBPHFaceRecognizer_create()

# Let's train our model 
model.train(np.asarray(Training_Data), np.asarray(Labels))
print("Model trained sucessefully")


# Run Our Facial Recognition
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

def face_detector(img, size=0.5):
    
    # Convert image to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray, 1.3, 5)
    
    if faces is ():
        return img, []
    
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)
        roi = img[y:y+h, x:x+w]
        roi = cv2.resize(roi, (200, 200))
    return img, roi


cap = cv2.VideoCapture(0)

while True:

    ret, frame = cap.read()
    
    image, face = face_detector(frame)
    
    try:
        face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)

        # Pass face to prediction model
        # "results" comprises of a tuple containing the label and the confidence value
        results = model.predict(face)
        print(results)
        if results[1] < 500:
            confidence = int( 100 * (1 - (results[1])/400) )
            display_string = str(confidence) + '% Confident it is User'
            
        cv2.putText(image, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
        
        if confidence > 75:
            cv2.putText(image, "Unlocked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
            cv2.imshow('Face Recognition', image )
            
        else:
            
            cv2.putText(image, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
            cv2.imshow('Face Recognition', image )

    except:
        cv2.putText(image, "Face not found", (220, 120) , cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
        cv2.imshow('Face Recognition', image )
        pass
        
    if cv2.waitKey(1) == 13: #13 is the Enter Key
        break
        
cap.release()
cv2.destroyAllWindows()   

该代码包括了人脸采集,训练和识别三个主要步骤。你可以按照以上步骤进行操作,并可以根据需要进行修改。
如果我的回答解决了您的问题,请采纳!

以下内容引用CHATGPT:

首先,你需要下载并安装Python环境,以及安装人脸识别库。你可以在命令行中输入以下命令来安装:

pip install face_recognition

接着,你需要下载并解压别人给的人脸识别系统文件,进入解压后的文件夹。在命令行中输入以下命令来运行该系统:

python face_recognition_system.py

系统会自动启动并进行人脸识别。如果你想要自己编写一个基于Python的人脸识别系统,可以参考face_recognition库的官方文档和示例代码。例如,以下代码可以识别一张图片中的人脸:

import face_recognition

# 加载图片文件
image = face_recognition.load_image_file("my_image.jpg")

# 获取图片中所有人脸的面部特征
face_landmarks_list = face_recognition.face_landmarks(image)

# 打印每个人脸的面部特征
for face_landmarks in face_landmarks_list:
    # 打印左眼的位置
    print("Left eye location:", face_landmarks["left_eye"])

你可以根据自己的需求,编写更加复杂的人脸识别系统。

  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7450559
  • 这篇博客也不错, 你可以看下python爬虫篇:为了追个漫画我居然用上爬虫,别人说我不讲武德
  • 除此之外, 这篇博客: 太牛逼了!用 Python 实现抖音上的“人像动漫化”特效,原来这么简单!中的 1)单纯的人像动漫化,不为人像戴口罩 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • import requests, base64
    # 这个函数的操作是为了获取access_token参数
    def get_access_token():
        url = 'https://aip.baidubce.com/oauth/2.0/token'
        data = {
            'grant_type': 'client_credentials',  # 固定值
            'client_id': '3j8EWb6rggzArSPY2X693LBy',  # 在开放平台注册后所建应用的API Key
            'client_secret': 'Px9KZuU0GleB0jTKktoCopnIWEiF57gf'  # 所建应用的Secret Key
        }
        res = requests.post(url, data=data)
        res = res.json()
        #print(res)
        access_token = res['access_token']
        return access_token
        
    # 下面的代码就是API文档中的代码,直接搬过来使用即可。
    request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
    f = open('zhao.jpg', 'rb')       # 二进制方式打开图片文件
    img = base64.b64encode(f.read()) # 图像转为base64的格式,这是百度API文档中要求的
    
    params = {"image":img}
    access_token = '24.11731cd1f00c59f9b3a930f917f3681b.2592000.1596894747.282335-21221990'
    request_url = request_url + "?access_token=" + get_access_token()
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    res = response.json()
    # 前面我们讲述了这个请求返回的是一个字典,其中一个键就是image,代表的是处理后的图像信息。
    # 将这个图像信息写入,得到最终的效果图。
    if res:
        f = open("kouzhao4.jpg", 'wb')
        after_img = res['image']
        after_img = base64.b64decode(after_img)
        f.write(after_img)
        f.close()
    
  • 您还可以看一下 王涛老师的150讲轻松学习Python网络爬虫课程中的 实战-12306抢票项目演示小节, 巩固相关知识点