当前位置:   article > 正文

局部二值模式直方图创建人脸识别器

局部二值模式直方图

先把代码搁这,纪录一下,可以直接运行摄像头检测:


import os

import cv2
import numpy as np
from sklearn import preprocessing

# Class to handle tasks related to label encoding
class LabelEncoder(object):
    # Method to encode labels from words to numbers
    def encode_labels(self, label_words):
        self.le = preprocessing.LabelEncoder()
        self.le.fit(label_words)

    # Convert input label from word to number
    def word_to_num(self, label_word):
        return int(self.le.transform([label_word])[0])

    # Convert input label from number to word
    def num_to_word(self, label_num):
        return self.le.inverse_transform([label_num])[0]

# Extract images and labels from input path
def get_images_and_labels(input_path):
    label_words = []

    # Iterate through the input path and append files
    for root, dirs, files in os.walk(input_path):
        for filename in (x for x in files if x.endswith('.jpg')):
            filepath = os.path.join(root, filename)
            label_words.append(filepath.split('\\')[-2]) 
            
    # Initialize variables
    images = []
    le = LabelEncoder()
    le.encode_labels(label_words)
    labels = []

    # Parse the input directory
    for root, dirs, files in os.walk(input_path):
        for filename in (x for x in files if x.endswith('.jpg')):
            filepath = os.path.join(root, filename)

            # Read the image in grayscale format
            image = cv2.imread(filepath, 0) 

            # Extract the label
            name = filepath.split('\\')[-2]
                
            # Perform face detection
            faces = faceCascade.detectMultiScale(image, 1.1, 2, minSize=(100,100))

            # Iterate through face rectangles
            for (x, y, w, h) in faces:
                images.append(image[y:y+h, x:x+w])
                labels.append(le.word_to_num(name))

    return images, labels, le

if __name__=='__main__':
    cascade_path =r'C:\Users\Administrator\Desktop\face\cascade_files\haarcascade_frontalface_alt.xml'
    path_train = r'C:\Users\Administrator\Desktop\face\train'
   
    
    # Load face cascade file
    faceCascade = cv2.CascadeClassifier(cascade_path)

    # Initialize Local Binary Patterns Histogram face recognizer
    recognizer = cv2.face.LBPHFaceRecognizer_create()

    # Extract images, labels, and label encoder from training dataset
    images, labels, le = get_images_and_labels(path_train)

    # Train the face recognizer 
    print( "\nTraining...")
    recognizer.train(images, np.array(labels))
    recognizer.save(r'C:\Users\Administrator\Desktop\face\train\a.xml')
    # Test the recognizer on unknown images
    print( '\nPerforming prediction on test images...')
    cap = cv2.VideoCapture(0)

# Define the scaling factor


# Loop until you hit the Esc key
    while True:
    # Capture the current frame and resize it
        ret, frame = cap.read()
        frame1=cv2.resize(frame, None, fx=0.5, fy=0.5,interpolation=cv2.INTER_AREA)
        gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
    #predict_image = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor,interpolation=cv2.INTER_AREA)
        faces = faceCascade.detectMultiScale(gray, 1.1,2, minSize=(100,100))
    # Convert to grayscale
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Run the face detector on the grayscale image
    #face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Draw rectangles on the image
        for (x, y, w, h) in faces:
                # Predict the output
            predicted_index, conf = recognizer.predict( gray[y:y+h, x:x+w])

                # Convert to word label
            predicted_person = le.num_to_word(predicted_index)

                # Overlay text on the output image and display it
            cv2.putText(frame1, predicted_person,   (10,60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3)
        cv2.imshow("Recognizing face", frame1)
    
        
        c = cv2.waitKey(5)
        if c == 27:
            break
    # Check if Esc key has been pressed


# Release the video capture object and close all windows
cap.release()
cv2.destroyAllWindows()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120

`

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/850075
推荐阅读
相关标签
  

闽ICP备14008679号