Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a simple but powerful face recognition system with Python

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to use Python to write a simple but powerful face recognition system, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can get something.

Face_recognition is a powerful, simple, easy-to-use face recognition open source project, and equipped with complete development documents and application cases, especially compatible with raspberry pie system. Face_recognition has been widely popular since it was released by open source, and its easy to use and powerful functions have become a very prominent label. Face_recognition is a very good tool for companies or some engineering practical application scenarios, and you don't need to have too much theoretical basis to complete an identification project more easily, so today we are going to explain it.

First, the open source address of the face_recognition project is here:

Https://github.com/ageitgey/face_recognition

There are relatively complete API instructions and example applications on the Internet, so I won't explain them here. First of all, using face_recognition requires installation, which can be done through pip. If the installation encounters an error, please refer to:

Https://yishuihancheng.blog.csdn.net/article/details/102679177

After the installation is complete, you can use it. You can verify whether the installation is successful by a simple test before coding, as shown below:

After successful installation, you can enter into use.

1. Locate the face in the image

Def demoFunc ():''image = face_recognition.load_image_file ("test.jpg") face_locations = face_recognition.face_locations (image) for one in face_locations: Y0, x1, y1, x0=one cv2.rectangle (image, pt1= (x0, y0), pt2= (x1, y1), color= (0,0,255) Thickness=3) cv2.imshow ('aaa', image) if cv2.waitKey (0) & 0xFF = = ord (' q'): cv2.destroyAllWindows ()

I randomly found a picture from the Internet, as follows:

The positioning results are as follows:

The feeling is still very powerful, of course, in the course of my practice, I also found that some image recognition failed to detect faces. After all, this is not a 100% problem. Face_recognition is more like a basic framework to help us build our own face recognition applications more efficiently.

2. Each face in the cut image is saved locally.

Def demoFunc ():''img = cv2.imread ("test.jpg") image = face_recognition.load_image_file ("test.jpg") face_locations = face_recognition.face_locations (image) # (top, right, bottom, left) for i in range (len (face_locations)): Y0, x1, y1 X0 = face_ locations [I] cropped = img.crop ((x0pjpg)) # (left, upper, right, lower) upper left corner, lower right corner cropped.save (str (I) + "_ .jpg") cropped.show ()

The original image used is the same as above, and the result is as follows:

All five faces have been successfully detected and saved successfully. Here, we should pay attention to the results returned by the face_locations function. Each sublist in the returned sublist contains four elements, namely, the coordinates of the upper left vertex and the lower right vertex of a single face image. The main thing to pay attention to is the order of these four parameters. The coordinates of the upper left vertex are represented in the result I give (x0meny0). (x1 ~ Y1) represents the coordinates of the lower right vertex.

3. Encode each face in the image into a 128-dimensional vector.

Def demoFunc ():''encode each face in the picture into a 128D vector' 'image = face_recognition.load_image_file ("cl.jpg") face_locations = face_recognition.face_locations (image) # (top, right, bottom, left) face_encodings = face_recognition.face_encodings (image) Face_locations) # converts a single face data into a 128D vector for one in face_encodings: print ('one:', one)

At this point, I have to talk about some of the application principles of face_recognition. Here are some of my summaries. Welcome to comment if there is any inappropriateness.

The principle of face recognition application in face_recognition module:

(1) give the picture of the face you want to recognize and encode it (only one for each person), and construct a list of these different face codes. Coding is actually mapping a face image into a 128-dimensional feature vector.

(2) calculate the similarity between image vectors to determine whether it is the same person according to the threshold or fault tolerance.

(3) output the identification result label.

It is no exaggeration to say that the core of face_recognition lies in the vectorization processing of this block, in which each input face image is transformed into a 128D feature vector for storage, and the 128D feature vector generation is also an algorithm. If you are interested in it, you can check it out and have an in-depth understanding. I will not expand here. After that, face recognition is transformed into the problem of vector similarity between two face images.

An image of Jackie Chan is used to test here, and the original image is as follows:

The results of vectorization are as follows:

If you want to build your own personalized application, you will generally choose to transform it here. The first thing is to save the feature vector here.

4. Input two face images to determine whether it is the same person.

Def demoFunc (one_pic='c1.jpg',two_pic='c2.jpg'):''given two pictures Determine whether it is the same person''chenglong = face_recognition.load_image_file (one_pic) unknown_image = face_recognition.load_image_file (two_pic) biden_encoding = face_recognition.face_encodings (chenglong) [0] unknown_encoding = face_recognition.face_encodings (unknown_image) [0] results = face_recognition.compare_faces ([biden_encoding], unknown_encoding) print (' results:' Results) return results [0]

This is actually a bit similar to the third part above, this part is based on the third part, but comes with the compare_faces similarity calculation interface, which can actually be replaced by itself.

Similarly, two images of Jackie Chan were used for the test, and the original image is as follows:

The test results are as follows:

5. Recognition and labeling of facial key points

Def demoFunc (pic_path='cl.jpg'):''facial key points recognition, Label''image = face_recognition.load_image_file (pic_path) face_landmarks_list = face_recognition.face_landmarks (image) print ("I found {} face (s) in this photograph." .format (len (face_landmarks_list) pil_image = Image.fromarray (image) d = ImageDraw.Draw (pil_image) for face_landmarks in face_landmarks_list: For facial_feature in face_landmarks.keys (): print ("The {} in this face has the following points: {}" .format (facial_feature Face_ landmarks [feature _ feature]) for facial_feature in face_landmarks.keys (): d.line (face_ landmarks [stories _ feature], width=5) pil_image.show ()

The key points of the face include: nose, mouth, eyes, eyebrows and so on. Here is the picture of Jackie Chan above, and the output below:

6. Make-up

This part is based on the fifth part, and the facial features obtained can be used for automatic makeup later. Here is the specific implementation:

Def demoFunc (pic_path= "haiwang.jpg"): image = face_recognition.load_image_file (pic_path) face_landmarks_list = face_recognition.face_landmarks (image) pil_image = Image.fromarray (image) for face_landmarks in face_landmarks_list: demo = ImageDraw.Draw (pil_image) 'RGBA') demo.polygon (face_landmarks [' left_eyebrow'], fill= (68,54,39,128)) demo.polygon (face_landmarks ['right_eyebrow'], fill= (68,54,39,128)) demo.line (face_landmarks [' left_eyebrow'], fill= (68,54,39,150), width=2) demo.line (face_landmarks ['right_eyebrow'], fill= (68,54,39,150) Width=2) demo.polygon (face_landmarks ['top_lip'], fill= (150,0,0,128)) demo.polygon (face_landmarks [' bottom_lip'], fill= (150,0,0,128)) demo.line (face_landmarks ['top_lip'], fill= (150,0,0,64), width=2) demo.line (face_landmarks [' bottom_lip'], fill= (150,0,0,64) Width=2) demo.polygon (face_landmarks ['left_eye'], fill= (255,255,255,30)) demo.polygon (face_landmarks [' right_eye'], fill= (255,255,255,30)) demo.line (face_landmarks ['left_eye'] + [face_landmarks [' left_eye'] [0]], fill= (0,0,0,110) Width=2) demo.line (face_landmarks ['right_eye'] + [face_landmarks [' right_eye'] [0]], fill= (0,0,0,110), width=2) pil_image.show ()

Here we use a picture of Sea King to test, and the original image is as follows:

The results are as follows:

It can also be something like this:

7. Build your own simple face recognition application based on face_recognition.

The above introduces a lot of face_recognition applications, here is the most important content, I think it is like this, based on the existing features to achieve our own personalized applications, I just simply throw a brick to attract jade, and give my own most simple implementation:

Def faceRecognitionDemo (picDir='data/', test_pic='test.png'):''build a face recognition module based on face_recognition' 'pic_list=os.listdir (picDir) for one_pic in pic_list: one_pic_path=picDir+one_pic one_res=demo6 (one_pic=one_pic_path) Two_pic=test_pic) one_name=one_pic.split ('.') [0] .strip () if one_res: print ('This Person is:', one_name) break else: print ('This Person is not:', one_name)

The screenshot of the data folder data is as follows:

The test.png content is as follows:

The output is as follows:

Of course, real-time computing is sure that the current calculation method can not be satisfied, this is only one of the simplest applications, just want to throw a brick to attract jade here, here is to call the face_recognition interface to complete the work of similar judgment Another very common method is that after obtaining the 128D feature vector of the face image, the face recognition problem can be transformed into a simple classification problem based on machine learning model, such as SVM, RF, GBDT and so on.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report