qq_36673487 2023-04-15 14:30 采纳率: 100%
浏览 74
已结题

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

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

  • 写回答

3条回答 默认 最新

  • 极客智能体-在线 2023-04-15 15:38
    关注

    以下答案由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()   
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月24日
  • 已采纳回答 4月16日
  • 创建了问题 4月15日

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗