Prerequisites (Windows)
- CMake
- Visual Studio C++ Build Tools
- Identifying The Detected Face
- Cropping Out The Detected Face
- Final Code For This Section
- Identifying The Detected Faces
- Cropping Out The Detected Faces
- Final Code For This Section
- Final Code For This Section
- Getting Face Encodings
- Checking For Matches
- Final Code For This Section
У цьому розділі, I'll go over some example usages of the Python face_recognition library to:
- Detect faces in images
- Detect facial features on a detected face (like eyebrows and nose)
- Check for matches detected faces
Всі зображення і коди сниппетів будуть виконані на цій post along with step-by-step instructions and explanations as to what is going on. Цей літературу спрямований на Windows 10, але Linux і macOS users буде найбільш добре find this easier як вони можуть skip деякі з пререquisites.
Тут є деякі важливі зв'язки для face_recognition if you need/want them:
Installing The "face_recognition" Library
Щоб налаштувати face_recognition library на Windows, ви повинні використовувати наступне:
Якщо ви не маєте цього, ви будете отримувати errors як,
CMake повинен бути налагоджений для будівництва наступних extensions: _dlib_pybind11
Which is telling you that CMake isn't installed, or,
Ви повинні використовувати Visual Studio для будівництва python extension on windows. Якщо ви запропонуєте цей error it means, ви не повинні керувати Visual C++. Зверніть увагу, що є багато flavours of Visual Studio, як Visual Studio для C# development. Ви повинні використовувати Visual Studio for C++.
Which is telling you that you need Visual Studio C++ build tools.
Натисніть CMake, go to cmake.org/download/ і download appropriate installer for your machine. I am using 64bit Windows 10 so I will get cmake - win64-x64.msi . Після downloading setup file, install it.
While installing CMake, add CMake до системи PATH довкілля навколишнього середовища для всіх користувачів або поточного користувача може бути надійно.
Після налаштування є досконалим, відкритим terminal і execute cmake . Це повинно виявляти використання для CMake. Якщо ви не збираєтеся, ви можете вибрати цю опцію до переходу до PATH навколишнього середовища.
Ви повинні потребувати close and re-open вашого terminal/application для PATH variable до update з бісером binary може бути identified.
Visual Studio C++ Build Tools
Unlike Linux, C++ комп'ютери для Windows не входять до OS. Якщо ви знайдете WindowsCompilers сторінку на witch Python ми можемо отримати інформацію про те, щоб отримати standalone version of Visual C++ 14.2 compiler без потреби для Visual Studio. Якщо ми бачимо link з того wiki section, ми будемо brought до Microsoft download page. На цій сторінці, яку ви бажаєте, ви хочете додати "Build Tools for Visual Studio 2019".
Wes vs_buildtools__.exe має downloaded, run the exe і дозволить йому налагодити кілька слів, щоб ми могли отримати на екрані нижче. When you get to this screen, make the selections I have:
Після того, як клацніть "Install", повертається до установки для завершення і повторного запуску.
Тепер, що CMake і необхідні будівельні інструменти будуть налагоджені, ми можемо продовжувати встановлювати face_recognition library.
Installing face_recognition and Verifying The Installation
Натисніть face_recognition library, execute the following in a terminal:
python -m pip install face-recognition
Це місце, щоб встановити довгий час, щоб налагодити, щоб використовувати як інструмент, який потрібно використовувати для інструментів, налаштованих з іншого. Для того, щоб validate, що library була успішно впроваджена, try to import the library в Python using the following:
import
face_recognition
No errors should be raised.
Для цього літератури, будуть також бути використані Pillow / PIL, які будуть використовуватися з скромними і draw на зображеннях. Це не вимагається, щоб використовувати face_recognition library, але буде необхідно в цьому словнику до prove/show результатів. Для того, щоб install it, execute the following:
python -m pip install Pillow
Для validate the library був налаштований, try to import PIL in Python using the following:
No errors should be raised.
Detecting Face In An Image
Тепер, що ми повинні налаштувати face_recognition library and PIL up, ми можемо почати помітні faces. Щоб запустити, ми повинні відмітити face in image with just one person.
Перший, ми хотіли б import face_recognition і деякі helpers з PIL.
import
face_recognition
from
PIL
import
Image,
ImageDraw
image
=
face_recognition.load_image_file('single-person.jpg')
image now contains our image в форматі, що face_recognition може помітити faces with. Визначте місце розташування цього зображення, Call face_recognition.face_locations and pass the image.
face_locations
=
face_recognition.face_locations(image)
face_locations will now contain a list of face locations. Чотири face location є низка pixel positions for (top, right, bottom, left) - ми повинні remember this for when use it later.
Безсумнівно, це є лише один матеріал в цьому малюнку, ми повинні expect будуть бути тільки одним пунктом в цьому списку. Для перевірки, як багато речей були виявлені, ми можемо отримати список сторінок.
amount
=
len(face_locations)
print(f'There are
amount>
face locations')
Для того, щоб отримати example image Я був здійснений вище і нам використовується для цього літератури, це буде мій, що був один face detected.
Для того, щоб вибрати цей пункт, щоб використати останній, ми можемо отримати в першу чергу з листа.
first_face_location
=
face_locations[0]
To see what's in this, you can call:
print(first_face_location)
Which will print out something like:
Вони є pixel positions for (top, right, bottom, left) які будуть використовуватися для створення box and crop with soon.
Identifying The Detected Face
Це означає, де face is that was detected in the image, we will draw a red box on the bounds that was returned by face_recognition.face_locations .
Перший, хто потребує створення PIL зображення від зображення, який був loaded using face_recognition.load_image_file . Doing this will allow us to use features offered by PIL.
img
=
Image.fromarray(image,
'RGB')
Тепер, що ми маємо PIL image, ми повинні створити об'єкт, щоб допомогти вам draw on the image. Крім того, вони будуть також скопіювати зображення в новий об'єкт з тим, коли ми потрапили в face out later the won't be a red box still around it.
img_with_red_box
=
img.copy()
img_with_red_box_draw
=
ImageDraw.Draw(img_with_red_box)
Тепер, що ми маємо об'єкт, щоб допомогти нам натиснути на зображення, будуть надписувати rectangle з використанням dimensions returned earlier.
Щоб витягнути box, ми повинні два пункти, верхній лівий і нижній правий x і y coordinates. Since we got back (top, right, bottom, left), we need to make these (left, top), (right, bottom); the basic translation can be seen below.
img_with_red_box_draw.rectangle(
[
(first_face_location[3],
first_face_location[0]),
(first_face_location[1],
first_face_location[2])
],
outline="red",
width=3
)
Всі необхідні (ліфт, top), (правий, нижній) для отримання (x, y) (x, y) пунктів.
У тому, що ми маємо також set outline="red" для створення box red і width=3 для створення box 3 pixels wide.
Щоб побачити результат, ми повинні:
img_with_red_box.show()
Це буде відкритий малюнок в деталі зображення переглядача. The image should look like this:
Cropping Out The Detected Face
Залишаючи з бік box, ми можемо потрапити з face в інший зображення.
Використовуючи оригінал зображення, що ми не пишуть на (тому що drew на зображеному зображенні), ми можемо записати img.
img_cropped
=
img.crop((
first_face_location[3],
# Left x
first_face_location[0],
# Top y
first_face_location[1],
# Right x
first_face_location[2]
# Bottom y
))
img.crop returns a copy of the original image being copped so you do not need to copy before-hand if you want to do something else with the original image.
img_cropped now contains a new cropped image, щоб відобразити його, ми можемо call .show() again.
Final Code For This Section
import
face_recognition
from
PIL
import
Image,
ImageDraw
# Detecting the faces
image
=
face_recognition.load_image_file('single-person.jpg')
# Load the image
face_locations
=
face_recognition.face_locations(image)
# Detect the face locations
first_face_location
=
face_locations[0]
# Get the first face
# Convert the face_recognition image to PIL image
img
=
Image.fromarray(image,
'RGB')
# Creating the image with red box
img_with_red_box
=
img.copy()
# Create a copy of original image with the is not red box in the cropped image later
img_with_red_box_draw
=
ImageDraw.Draw(img_with_red_box)
# Create an image to draw with
img_with_red_box_draw.rectangle(
# Draw the rectangle on the image
[
(first_face_location[3],
first_face_location[0]),
# (Left, top)
(first_face_location[1],
first_face_location[2])
# (right, bottom)
],
outline="red",
# Make the box red
width=3
# Make the box 3px in thickness
)
img_with_red_box.show()
# Open the image in the default image viewer
# Creating the cropped image
img_cropped
=
img.crop((
# Crop the original image
first_face_location[3],
first_face_location[0],
first_face_location[1],
first_face_location[2]
))
img_cropped.show()
# Open the image in the default image viewer
Detecting Multiple Faces In Image
We saw before that face_recognition.face_locations returns array of tuples corresponding with the locations of faces. Це означає, що ми можемо використовувати самі методи вище, але проміжок результату face_recognition.face_locations коли drawing and cropping.
I will use the following as my image. Це має 5 faces visible, 2 of which are slightly blurred.
Після того, як буде import face_recognition і деякі helpers з PIL.
import
face_recognition
from
PIL
import
Image,
ImageDraw
Натисніть на новий малюнок, використовуючи face_recognition.load_image_file і відмітьте faces, використовуючи ті самі методи, як перед.
image
=
face_recognition.load_image_file('group-of-people.jpg')
face_locations
=
face_recognition.face_locations(image)
Якщо ми виконаємо face_locations ( print(face_locations) ), ми можемо думати, що 5 faces мають бути визначені.
[
(511,
1096,
666,
941),
(526,
368,
655,
239)
(283,
1262,
390,
1154),
(168,
1744,
297,
1615),
(271,
390,
378,
282)
]
Since we now have more than one face, that first one does not make sense - we should loop over them all and perform our operations in the loop.
Після того, як ми продовжуємо, ми повинні також створювати PIL image будуть працювати з.
img
=
Image.fromarray(image,
'RGB')
Identifying The Detected Faces
Більше, ми повинні скопіювати оригінал зображення для останнього (опційний) і створити об'єкт для введення в текст.
img_with_red_box
=
img.copy()
img_with_red_box_draw
=
ImageDraw.Draw(img_with_red_box)
Now we can loop all the faces and create rectangles.
for
face_location
in
face_locations:
img_with_red_box_draw.rectangle(
[
(face_location[3],
face_location[0]),
(face_location[1],
face_location[2])
],
outline="red",
width=3
)
And once again, look at the image:
img_with_red_box.show()
Cropping Out The Detected Faces
Just like drawing many boxes, we can also crop all the detected faces. Використовуйте для-запуску зображення, покладіть зображення в будь-який проміжок і буде показувати зображення.
for
face_location
in
face_locations:
img_cropped
=
img.crop((face_location[3],
face_location[0],
face_location[1],
face_location[2]))
img_cropped.show()
Ви будете мати кілька зображень, які відкриті на вашому комп'ютері в окремих windows; там вони є всі:
Я має вгорурозгорнуті ці зображення для літератури, але ваші будуть розбиті на будь-якому розв'язанні ви запускаєтеся.
Final Code For This Section
import
face_recognition
from
PIL
import
Image,
ImageDraw
# Load image and detect faces
image
=
face_recognition.load_image_file("group-of-people.jpg")
face_locations
=
face_recognition.face_locations(image)
# Create the PIL image to copy and crop
img
=
Image.fromarray(image,
'RGB')
img_with_red_box
=
img.copy()
# Make a single copy for all the red boxes
img_with_red_box_draw
=
ImageDraw.Draw(img_with_red_box)
# Get our drawing object again
for
face_location
in
face_locations:
# Loop over all the faces detected this time
img_with_red_box_draw.rectangle(
# Draw a rectangle for the current face
[
(face_location[3],
face_location[0]),
(face_location[1],
face_location[2])
],
outline="red",
width=3
)
img_with_red_box.show()
# Open the image in the default image viewer
for
face_location
in
face_locations:
# Loop over all the faces detected
img_cropped
=
img.crop((
# Crop the current image like we did last time
face_location[3],
face_location[0],
face_location[1],
face_location[2]
))
img_cropped.show()
# Show the image for the current iteration
Identifying Facial Features
face_recognition also has function face_recognition.face_landmarks, які працюють як face_recognition.face_locations but будуть відновити список опцій, що беруть участь в face feature positions, останнє, ніж positions of detected faces themselves.
Перейти до зображення з однією людиною в ньому, ми можемо import everything again, load the image and call face_recognition.face_landmarks .
import
face_recognition
from
PIL
import
Image,
ImageDraw
image
=
face_recognition.load_image_file('single-person.jpg')
face_landmarks_list
=
face_recognition.face_landmarks(image)
# The new call
Now if we print face_landmarks_list , object will look a bit different.
[
'chin':
[(315,
223),
(318,
248),
(321,
273),
(326,
296),
(335,
319),
(350,
339),
(370,
354),
(392,
365),
(415,
367),
(436,
363),
(455,
351),
(469,
336),
(479,
318),
(486,
296),
(488,
273),
(490,
251),
(489,
229)],
'left_eyebrow':
[(329,
194),
(341,
183),
(358,
180),
(375,
182),
(391,
189)],
'right_eyebrow':
[(434,
189),
(448,
184),
(461,
182),
(474,
184),
(483,
194)],
'nose_bridge':
[(411,
209),
(411,
223),
(412,
238),
(412,
253)],
'nose_tip':
[(394,
269),
(403,
272),
(412,
275),
(421,
272),
(428,
269)],
'left_eye':
[(349,
215),
(360,
208),
(373,
207),
(384,
216),
(372,
218),
(359,
219)],
'right_eye':
[(436,
216),
(446,
208),
(458,
208),
(467,
216),
(459,
219),
(447,
219)],
'top_lip':
[(374,
309),
(388,
300),
(402,
296),
(411,
298),
(420,
296),
(434,
301),
(448,
308),
(442,
308),
(420,
307),
(411,
308),
(402,
307),
(380,
309)],
'bottom_lip':
[(448,
308),
(434,
317),
(421,
321),
(411,
322),
(401,
321),
(388,
317),
(374,
309),
(380,
309),
(402,
309),
(411,
310),
(421,
309),
(442,
308)]
>
]
Там є quite a bit of stuff here. Для кожного facial feature (i.e. chin, left eyebrow, right eyebrow, etc), a corresponding list contains x and y tuples - thes x and y points are x and y coordinates on the image.
PIL offers a .line() метод на зображенні об'єкта будуть бути використані, які мають список x і y пунктів, які є сприятливим для цього. To start we will need a drawing object.
img
=
Image.fromarray(image,
'RGB')
# Make a PIL image from the loaded image
img_draw
=
ImageDraw.Draw(img)
# Create the draw object
In this example we will not copy the image as this is the only time we will be using it
Тепер, що ми маємо об'єкт, щоб допомогти вам витягнути, plot всі ці лінії, використовуючи першу думку в розділі, що повернулися до.
face_landmarks
=
face_landmarks_list[0]
# Get the first dictionary of features
img_draw.line(face_landmarks['chin'])
img_draw.line(face_landmarks['left_eyebrow'])
img_draw.line(face_landmarks['right_eyebrow'])
img_draw.line(face_landmarks['nose_bridge'])
img_draw.line(face_landmarks['nose_tip'])
img_draw.line(face_landmarks['left_eye'])
img_draw.line(face_landmarks['right_eye'])
img_draw.line(face_landmarks['top_lip'])
img_draw.line(face_landmarks['bottom_lip'])
Now we can call .show() on our image to look at it:
Final Code For This Section
import
face_recognition
from
PIL
import
Image,
ImageDraw
# Load the image and detect face landmarks for each face within
image
=
face_recognition.load_image_file('single-person.jpg')
face_landmarks_list
=
face_recognition.face_landmarks(image)
# Make a PIL image from the loaded image and then get a drawing object
img
=
Image.fromarray(image,
'RGB')
img_draw
=
ImageDraw.Draw(img)
# Draw all the features for first face
face_landmarks
=
face_landmarks_list[0]
# Get the first object corresponding to the first face
img_draw.line(face_landmarks['chin'])
img_draw.line(face_landmarks['left_eyebrow'])
img_draw.line(face_landmarks['right_eyebrow'])
img_draw.line(face_landmarks['nose_bridge'])
img_draw.line(face_landmarks['nose_tip'])
img_draw.line(face_landmarks['left_eye'])
img_draw.line(face_landmarks['right_eye'])
img_draw.line(face_landmarks['top_lip'])
img_draw.line(face_landmarks['bottom_lip'])
img_with_face_landmarks.show()
# Show the image for the current iteration
Matching Detected Faces
face_recognition library такожвикористовує function face_recognition.compare_faces ,які можуть бути використані для compare detected faces для повідомлень, якщо вони беруть участь.
Є два arguments for this function which we will use:
- known_face_encodings : A list of known face encodings
- face_encoding_to_check : A single face encoding to compare against the list
Для цієї секції, будуть бути 2 face encodings для самої людини і вимагати, якщо вони є в іншому малюнку.
Тут є два зображення з відомим face in each:
And here are the images we will check to see if Elon is in them:
Getting Face Encodings
Для отримання популярних face encodings, ми можемо використовувати face_recognition.face_encodings . Ця функція складається з зображення, яке містить face and locations of faces in images to use.
Typically you would only use one location of face in single image to create one encoding but if you have multiple of the same face in one image you can provide more than one location.
Процес того, що ми потрібні для того, щоб отримати наш відомий face encodings is:
- Load in the first image
- Detect faces in the image to get the face locations
- Verify there is only one face and select the first face
- Call face_recognition.face_encodings з зображенням і одним face location
- Repeat 1 through 5 for second image
We have done steps 1-3 previously, so we can do it here again:
import
face_recognition
# Load image and detect faces
image
=
face_recognition.load_image_file("elon-musk-1.jpg")
face_locations
=
face_recognition.face_locations(image)
And to validate one face was detected:
print(len(face_locations))
# Should be 1
Now we can call face_recognition.face_encodings і забезпечує зображення і розташування location.
face_location
=
face_locations[0]
# We тільки want an encoding for the first face. Вони можуть бути більше, ніж один face в зображеннях ви використовуєте, що я можу це зробити, як ні.
face_encodings
=
face_recognition.face_encodings(image,
[face_location])
Parameter known_face_locations is optional and face_recognition буде помітити всі faces в image автоматично, коли get face encodings if known_face_locations is not supplied.Для цього пункту, I demstrating it this way to validate there is only one detected face in the image.
Since буде specified array of known_face_locations , ми знаємо, що там буде тільки один цукерок, що повернувся, якщо ми можемо вперше.
elon_musk_knwon_face_encoding_1
=
face_encodings[0]
We can now repeat цей процес для іншого зображення
image
=
face_recognition.load_image_file("elon-musk-2.png")
# Load the image
face_locations
=
face_recognition.face_locations(image)
# Get face locations
face_location
=
face_locations[0]
# Only use the first detected face
face_encodings
=
face_recognition.face_encodings(image,
[face_location])
# Get all face encodings
elon_musk_knwon_face_encoding_2
=
face_encodings[0]
# Pull out the 1 returned face encoding
Тепер, що ми маємо elon_musk_knwon_face_encoding_1 і elon_musk_knwon_face_encoding_2 , ми можемо, якщо вони існують у наших інших двох зображеннях.
Checking For Matches
Щоб виконати матчі в зображення з face_recognition.compare_faces , нам потрібні відомі face encodings (який буде тільки gotten above) and a single face encoding to check.
Безсумнівно, ми працюємо з групами знімків, ми повинні йти до вимкнених повідомлень - тільки тому, що буде працювати самотужки з тільки однією людиною в зображення.
Перший, хто потребує отримати всі face decodings з нашого першого зображення до compare. Я був помічений про те, що другий параметр, known_face_locations , до face_recognition.face_encodings був опціональним, керував ним, щоб помітити всі faces в зображенні автоматично і повторний face encodings для every face in the image; this is exactly what we want and will remove the intermediate step of detecting faces.
image
=
face_recognition.load_image_file("elon-musk-in-group.jpg")
# Load the image we are comparing
unknwon_face_encodings
=
face_recognition.face_encodings(image)
# Get face encodings for everyone in the image
Тепер, що ми маємо наш незрозумілий face encodings for all the faces в групі зображення, ми можемо вимкнути над ними і виконати eether match:
for
unknwon_face_encoding
in
unknwon_face_encodings:
matches
=
face_recognition.compare_faces(
[elon_musk_knwon_face_encoding_1,
elon_musk_knwon_face_encoding_2],
# The known face encodings (can be only 1 - less is faster)
unknwon_face_encoding
# The single unknown face encoding
)
print(matches)
If you run this, you will see something like:
[True,
True]
[False,
False]
[False,
False]
[False,
False]
Її лінію є один варіант (отриманий в матчах) і всі boolean відповідають на відомий face encoding і whether it matched unknown face encoding.
З величини вище, ми можемо побачити, що перший незабутній face в групі зображення охоплюють ланцюжок пізній face encodings і інші три unknown faces не піднімають її нікому. Використовуючи більше, ніж один face прокинутися можна тільки для того, щоб визначити, що можлива, але буде вартість вас в швидкості.
Якщо ви збираєтеся це на іншому малюнку, всіповертаються false.
Final Code For This Section
import
face_recognition
# Load elon-musk-1.jpg and detect faces
image
=
face_recognition.load_image_file("elon-musk-1.jpg")
face_locations
=
face_recognition.face_locations(image)
# Get the single face encoding out of elon-musk-1.jpg
face_location
=
face_locations[0]
# Only use the first detected face
face_encodings
=
face_recognition.face_encodings(image,
[face_location])
elon_musk_knwon_face_encoding_1
=
face_encodings[0]
# Pull out the 1 returned face encoding
# Load elon-musk-2.jpg and detect faces
image
=
face_recognition.load_image_file("elon-musk-2.png")
face_locations
=
face_recognition.face_locations(image)
# Get the single face encoding out of elon-musk-2.jpg
face_location
=
face_locations[0]
face_encodings
=
face_recognition.face_encodings(image,
[face_location])
elon_musk_knwon_face_encoding_2
=
face_encodings[0]
# Load the image with unknown to compare
image
=
face_recognition.load_image_file("elon-musk-in-group.jpg")
# Load the image we are comparing
unknwon_face_encodings
=
face_recognition.face_encodings(image)
# Loop over each unknwon face encoding to see if the face matches either known encodings
print('Matches for elon-musk-in-group.jpg')
for
unknwon_face_encoding
in
unknwon_face_encodings:
matches
=
face_recognition.compare_faces(
[elon_musk_knwon_face_encoding_1,
elon_musk_knwon_face_encoding_2],
# The known face encodings (can be only 1 - less is faster)
unknwon_face_encoding
# The single unknown face encoding
)
print(matches)
# Load the other image with unknown to compare
image
=
face_recognition.load_image_file("group-of-people.jpg")
# Load the image we are comparing
unknwon_face_encodings
=
face_recognition.face_encodings(image)
# Loop over each unknwon face encoding to see if the face matches either known encodings
print('Matches for group-of-people.jpg')
for
unknwon_face_encoding
in
unknwon_face_encodings:
matches
=
face_recognition.compare_faces(
[elon_musk_knwon_face_encoding_1,
elon_musk_knwon_face_encoding_2],
unknwon_face_encoding
)
print(matches)
Additional PIL Help
Цей tutorial не фокусується на PIL, але одна функція може бути використана is img.save() ; this saves a file. Докладніше про його використання є img.save('my_image.png') для збереження PIL image для my_image.png.
Ви можете побачити більше на PIL в його docs і є поряд з іншим пристосуванням, як він є дуже old library.
Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.