In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 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 system based on opencv and pillow". The content of the explanation is simple and clear, and it is easy to learn and understand. now please follow the editor's train of thought to study and learn "how to realize face recognition system based on opencv and pillow".
This paper does not involve algorithm principles such as classifier and training recognizer, but only contains its application (I will also write my own views and understanding of the principle of machine learning algorithm in the future)
First of all, we need to know that it is not difficult to make a face recognition system using the existing framework, and then let's start our system development.
Our system is mainly divided into three parts, and then I will propose a solution that can not add Chinese to the catch-up images. What we need to accomplish: 1. Face detection and data collection 2. Training recognizer 3. Face recognition and display
Before reading this article, I believe you have done the deployment of the python environment and the download and installation of the opencv module. Now the module we need is pillow (the raspberry pie comes with this module by default, but if you are using the win system, you may need to install it by typing pip install pillow on the terminal), and the opencv-contrib module, the face module of cv2 is included (of course, the raspberry pie of my Linux system still seems to include this module by default. So if you are using pc, you may need to download it separately), as well as the most basic numpy module.
Before we start writing code, we first need to add two folders to the current running directory. Dataset is used to store the captured face images, which is convenient to train the recognizer later, and the trainer folder stores the training results.
one. Face detection and data collection # data acquisition cam = cv2.VideoCapture (0) # catch image cam.set (3640) # set video widthcam.set (4480) # set video heightface_detector = cv2.CascadeClassifier ('haarcascade_frontalface_default.xml') # Import classifier # For each person, enter one numeric face idface_id = input ('\ ninput user id') print ("\ ndata acquisition") Please face up to the slight twist of the camera ") # Initialize individual sampling face countcount = 0while (True): ret, img = cam.read () # ret is whether it has been read successfully, it is a Boolean value gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY) # converted into a grayscale image faces = face_detector.detectMultiScale (gray, 1.3,5 mins Size = (100100)) for (xQuery in faces:# h) where faces is an array array or empty tuple. The reason I will analyze later is cv2.rectangle (img, (xrem y), (xonomwrecy), (255Let0), 2) count + = 1 # Save the captured image into the datasets folder cv2.imwrite ("dataset/User." + str (face_id) +'.'+ str (count) + ".jpg", gray [ycount (image')]) cv2.imshow Img) k = cv2.waitKey & 0xff # Press' ESC' for exiting video if k = 27: break elif count > = 10: # Take 10 face sample and stop video break# Do a bit of cleanupprint ("\ n [INFO] Exiting Program and cleanup stuff") cam.release () cv2.destroyAllWindows ()
In this part, we complete the face acquisition, save it in our dataset folder, and express each person's data in a specific id, so that we can train recognizers that can recognize different faces. The second parameter in cam.set step is the image resolution. 640 × 480 is the default resolution of opencv, but it still supports 800x600 and a maximum of 1280 x 1024 pixels. Even if the maximum allowable resolution of your camera is much higher than this value, opencv still doesn't seem to allow you to use it. Then there is the import of the haar cascade classifier. During the configuration process, we have downloaded the classifier that comes with opencv. You only need to look for the file haarcascade_frontalface_default.xml in the file manager. There are many classifiers in the folder where this file is located. Of course, if you want to recognize objects such as apples and bananas, you may need to train new classifiers (which is also easy to do). This article discusses face recognition. So I'm not going to repeat it here, you can choose to import it with its absolute path, or you can copy it to your current directory as I did. Then enter the loop, read the image-> convert the grayscale image, then use the classifier you have imported to recognize other people's faces and mark them with boxes, and then store the pictures in the box in the dataset folder. It is worth mentioning that, because the classifier algorithm is very slow, so the classifier itself has frame reduction processing (even so my raspberry pie with face recognition system is still very difficult), so faces should be most of the time is empty tuples, a small part of the time is to read the array array, so you need to pay special attention to the indentation problem, do not let the classifier itself reduced frames affect the number of frames you read and display video.
two。 Training recognizer import cv2# trainer import numpy as npfrom PIL import Imageimport os# Path for face image databasepath = 'dataset'recognizer = cv2.face.LBPHFaceRecognizer_create () # Import of recognizer detector = cv2.CascadeClassifier ("haarcascade_frontalface_default.xml") # function to get the images and label datadef getImagesAndLabels (path): imagePaths = [os.path.join (path,f) for f in os.listdir (path)] # here the os module can help us establish the path very well It is recommended that you first take a look at the use of related functions. FaceSamples= [] ids = [] for imagePath in imagePaths: PIL_img = Image.open (imagePath). Convert ('L') # into a grayscale image img_numpy = np.array (PIL_img,'uint8') # convert into an array id = int (os.path.split (imagePath) [- 1] .split (".") [1]) faces = detector.detectMultiScale (img_numpy) for X:x+w]) ids.append (id) return faceSamples,idsprint ("\ n training data" Please wait ") faces,ids = getImagesAndLabels (path) recognizer.train (faces, np.array (ids)) # Save the model into trainer/trainer.ymlrecognizer.write ('trainer/trainer.yml') # recognizer.save () worked on Mac, but not on Pi# Print the numer of faces trained and end programprint ("\ n {0} face training completed. The program closes ".format (len (np.unique (ids)
In this step, we need to train the recognizer according to different id and save the results, and write the summary of the results into the trainer folder named trainer.yml. In this file is the trained recognizer.
three。 Face recognition and display #-*-coding: UTF-8-*-# recognizer import cv2import numpy as npimport osfrom PIL import Image, ImageFont, ImageDrawpath_to_ttf ='C:\ Windows\ Fonts\ Microsoft YaHei UI\ msyh.ttc'#ttc file is a font that supports Chinese, which I will explain later. Font1= ImageFont.truetype (path_to_ttf, size=20) recognizer = cv2.face.LBPHFaceRecognizer_create () recognizer.read ('trainer/trainer.yml') # read recognizer cascadePath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier (cascadePath) Font = cv2.FONT_HERSHEY_SIMPLEX#iniciate id counterid = "names related to ids: example = = > Marcelo: id=1, etcnames = ['None',' Duan Linchen', 'Paula',' Ilza', 'Zhuan,' W'] # because we will not only display your code name but your specific information in face recognition. Cam = cv2.VideoCapture (0) cam.set (3640) # set video widhtcam.set (4480) # set video height# the size of the minimum recognized face, in the recognition process, we will not capture the information of passers-by far away from you, which will lead to a lot of problems, so we only need to identify the people who want to participate in the recognition Setting the minimum face recognition size can circumvent this point: minW = 0.1*cam.get (3) minH = 0.1*cam.get (4) while True: ret, img = cam.read () gray = cv2.cvtColor (img,cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale (gray, scaleFactor = 1.2, minNeighbors = 5, minSize = (int (minW), int (minH),) # related parameters can be set to search for (xjaoyjiaow. H) in faces: cv2.rectangle (img, (xmemy), (xonomy), (0meme 255), 2) id, confidence = recognizer.predict (gray [gray]) # Check if confidence is less them = > "0" is perfect match if (confidence < 100): id = names [id] confidence = "{0}%" .format (round (confidence)) # confidence is the confidence index Equal to 100-probability I believe that your probabilities and statistics must be better than mine: id = "unrecognized" confidence = "{0}%" .format (round (100-confidence)) img=Image.fromarray (img) draw = ImageDraw.Draw (img) draw.text (xy= (xtrem5lyric 5), text=str (id), font=font1,fill= (255255255)) img=np.array (img) cv2.putText (img, str (confidence), (xpend5, str (confidence)), font, 1, (255Power255) 0) 1) cv2.imshow ('camera',img) k = cv2.waitKey (10) & 0xff # Press' ESC' for exiting video if k = = 27: break# Do a bit of cleanupprint ("\ n [INFO] Exiting Program and cleanup stuff") cam.release () cv2.destroyAllWindows ()
In this step, it is a pity that the cv2.putText function does not support Chinese applications, that is, you cannot display Chinese names in the video through this function, although you may have English names or simply use Hanyu pinyin, but this problem must be solved. So we introduce the pillow module here, we only need to use the img.draw function to type your name on the picture first, and then the cv2.putText function can solve this problem very well, but the trouble is that the picture types involved in these two functions are different, so I converted the img and array images in the code, and finally completed the face recognition system.
Thank you for reading, the above is the content of "how to realize face recognition system based on opencv and pillow". After the study of this article, I believe you have a deeper understanding of how to realize face recognition system based on opencv and pillow, 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.