In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to realize face recognition based on Opencv in Python". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to realize face recognition based on Opencv in Python".
Detect faces. This should be the most basic, give us a picture, we have to detect the area of the face, and then we can
To operate, opencv has built in a lot of classification detectors, so this time we use haar:
Def detect_face (img): # converts the test image to grayscale image, because opencv face detector requires grayscale image gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY) # load OpenCV face detection classifier Haar face_cascade = cv2.CascadeClassifier ('. / haarcascade_frontalface_default.xml') # to detect multi-scale images The return value is a list of facial region information (XMagney, width, height) faces = face_cascade.detectMultiScale (gray, scaleFactor=1.2, minNeighbors=5) # if no face is detected, the original image if (len (faces) = = 0) is returned: return None, None # currently assumes only one face, and xy is the upper-left coordinates Wh is the width and height of the rectangle (x, y, w, h) = faces [0] # returns the front part of the image return gray [YRV y + w, XRO x + h], faces [0]
two。 With the dataset and face detection function, we can conduct pre-training and finally return the face detection information and tags of all the training images:
# this function will read all the training images, detect faces from each image, and return two lists of the same size Def prepare_training_data (data_folder_path): # get the directory in the data folder (one directory for each topic) dirs = os.listdir (data_folder_path) # two lists save all the faces and tags faces = [] labels = [] # browse each directory and access the images for dir_name in dirs: # dir_name (str class) Type) that is, the label label = int (dir_name) # establishes the directory path containing the current theme image subject_dir_path = data_folder_path + "/" + dir_name # gets the image name in the given theme directory subject_images_names = os.listdir (subject_dir_path) # browses each picture and detects the face Then add the face information to the face list faces [] for image_name in subject_images_names: # establish the image path image_path = subject_dir_path + "/" + image_name # read the image image = cv2.imread (image_path) # display image 0.1s cv2.imshow ("Training on image...", image) cv2.waitKey (100) # detect the face face Rect = detect_face (image) # We ignore the undetected face if face is not None: # add the face to the face list and add the corresponding tag faces.append (face) labels.append (label) cv2.waitKey (1) cv2.destroyAllWindows () # the final return value is the face and tag list return faces, labels
3. With the facial information and corresponding tags, we can use opencv's own recognizer for training:
# call the prepare_training_data () function faces, labels = prepare_training_data ("training_data") # create a LBPH recognizer and start training. Of course, you can also choose Eigen or Fisher recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create () face_recognizer.train (faces, np.array (labels))
4. The prediction can be made after training, and before that, we can set the format of the prediction, including using a rectangle to frame the human face and marking its name, and of course, don't forget to set up a direct mapping table between the tag and the real name:
# draw a rectangle def draw_rectangle (img, rect): (xPowery, w, h) = rect cv2.rectangle (img, (xPowery), (x + w, y + h), (128,128,0), 2) # according to the given (x) Y) coordinates identify the name def draw_text (img, text, x, y): cv2.putText (img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128,128,0), 2) # create a mapping list between tags and names (tags can only be integers) subjects = ["jiaju", "jiaqiang"]
5. Now we can define our prediction function:
# this function identifies the person in the passed image and draws a rectangle and its name def predict (test_img): # around the detected face to make a copy of the image In this way, we can retain the original image img = test_img.copy () # detect the face face, rect = detect_face (img) # predict the face label = face_recognizer.predict (face) # get the name of the corresponding tag label_text = subjects [label [0]] # draw a rectangle draw_rectangle (img, rect) # around the detected face and mark the predicted name draw_text (img, label_text) Rect [0], rect [1]-5) # returns the predicted image return img
6. Finally, use the picture in our test_data to predict and show the final result:
# load test image test_img1 = cv2.imread ("test_data/test1.jpg") test_img2 = cv2.imread ("test_data/test2.jpg") # execute prediction predicted_img1 = predict (test_img1) predicted_img2 = predict (test_img2) # display two images cv2.imshow (subjects [0], predicted_img1) cv2.imshow (subjects [1], predicted_img2) cv2.waitKey (0) cv2.destroyAllWindows ()
Let's take a look at the recognition results:
This is the most basic process of face recognition, and there will be further research. In the next article, we will discuss some details and matters needing attention of this experiment, which can be regarded as a mining and summary of this article. Finally, the complete code is attached:
# #-*-coding:utf-8-*-import cv2import osimport numpy as np# face detection def detect_face (img): # convert the test image to grayscale image, because opencv face detector requires grayscale image gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY) # load OpenCV face detection classifier Haar face_cascade = cv2.CascadeClassifier ('. / haarcascade_frontalface_default.xml') # detect multi-scale image The return value is a list of facial region information (XMagney, width, height) faces = face_cascade.detectMultiScale (gray, scaleFactor=1.2, minNeighbors=5) # if no face is detected, the original image if (len (faces) = = 0) is returned: return None, None # currently assumes only one face, and xy is the upper-left coordinates Wh is the width and height of a rectangle (x, y, w, h) = faces [0] # returns the front part of the image return gray [YVV y + w, XRV x + h], faces [0] # this function will read all the training images, detect faces from each image and return two lists of the same size Def prepare_training_data (data_folder_path): # get the directory in the data folder (one directory for each topic) dirs = os.listdir (data_folder_path) # two lists save all the faces and tags faces = [] labels = [] # browse each directory and access the images for dir_name in dirs: # dir_name (str class) Type) that is, the label label = int (dir_name) # establishes the directory path containing the current theme image subject_dir_path = data_folder_path + "/" + dir_name # gets the image name in the given theme directory subject_images_names = os.listdir (subject_dir_path) # browses each picture and detects the face Then add the face information to the face list faces [] for image_name in subject_images_names: # establish the image path image_path = subject_dir_path + "/" + image_name # read the image image = cv2.imread (image_path) # display image 0.1s cv2.imshow ("Training on image...", image) cv2.waitKey (100) # detect the face face Rect = detect_face (image) # We ignore the undetected face if face is not None: # add the face to the face list and add the corresponding tag faces.append (face) labels.append (label) cv2.waitKey (1) cv2.destroyAllWindows () # the final return value is the face and tag list return faces, labels# calls the prepare_training_data () function faces, labels = prepare_training_data ("training_data") # to create a LBPH recognizer and start training Of course, you can also choose Eigen or Fisher recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create () face_recognizer.train (faces, np.array (labels)) # according to the given (x Y) draw a rectangle def draw_rectangle (img, rect): (x, y, w, h) = rect cv2.rectangle (img, (x, y), (x + w, y + h), (128,128,0), 2) # according to the given (x Y) coordinates identify def draw_text (img, text, x, y): cv2.putText (img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128,128,0), 2) # create a mapping list between tags and names (tags can only be integers) subjects = ["jiaju" "jiaqiang"] # this function identifies the person in the transferred image and draws a rectangle and its name def predict (test_img): # around the detected face to make a copy of the image In this way, we can retain the original image img = test_img.copy () # detect the face face, rect = detect_face (img) # predict the face label = face_recognizer.predict (face) # get the name of the corresponding tag label_text = subjects [label [0]] # draw a rectangle draw_rectangle (img, rect) # around the detected face and mark the predicted name draw_text (img, label_text) Rect [0], rect [1]-5) # return predicted image return img# load test image test_img1 = cv2.imread ("test_data/test1.jpg") test_img2 = cv2.imread ("test_data/test2.jpg") # execute prediction predicted_img1 = predict (test_img1) predicted_img2 = predict (test_img2) # display two images cv2.imshow (subjects [0], predicted_img1) cv2.imshow (subjects [1] Predicted_img2) cv2.waitKey (0) cv2.destroyAllWindows () Thank you for your reading The above is the content of "how to realize face recognition based on Opencv in Python". After the study of this article, I believe you have a deeper understanding of how to achieve face recognition based on Opencv in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.