赞
踩
先把代码搁这,纪录一下,可以直接运行摄像头检测:
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()
`
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。