Reputation: 174
How can I get the pixel coordinates of the top of the head for a headshot image in Python?
I've taken a look at dlib
with https://github.com/codeniko/shape_predictor_81_face_landmarks as well as the face_recognition
module, but neither of them seem to support
Here's the script I've written
# /// script
# dependencies = [
# "cmake",
# "pillow",
# "face_recognition",
# "dlib",
# ]
# ///
import argparse
from pathlib import Path
import dlib
import face_recognition
from PIL import Image, ImageDraw
def main(image_path):
image = face_recognition.load_image_file(image_path)
return features(image)
def features(image):
# face_recognition
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[facial_feature]))
for facial_feature in face_landmarks.keys():
d.line(face_landmarks[facial_feature], width=2)
locations = face_recognition.face_locations(image)
for top, right, bottom, left in locations:
d.line([(left, top), (right, top), (right, bottom), (left, bottom), (left, top)], width=2)
# dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(str(Path(__file__).parent / 'shape_predictor_81_face_landmarks.dat'))
faces = detector(image)
for face in faces:
x1 = face.left()
y1 = face.top()
x2 = face.right()
y2 = face.bottom()
landmarks = predictor(image, face)
for part in landmarks.parts():
d.circle((part.x, part.y), 2, width=0, fill='white')
# Show the picture
pil_image.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process an image to create a proportional passport photo.")
parser.add_argument("image", help="Path to the image file (jpeg, png, tiff)")
args = parser.parse_args()
main(args.image)
and its output:
But the point I am interested in is this one, where the crown of the head would be predicted to be:
How can I get that point in Python?
Upvotes: 1
Views: 35