Home > Software engineering >  How can I run through a folder of images automatically and obtain the 468 facial landmark coordinate
How can I run through a folder of images automatically and obtain the 468 facial landmark coordinate

Time:09-28

This is my code which can run without any problem. However, I do not want to move from one image to another image manually as I have more than 2000 images in the folder. What do I need to edit to automatically run through the images from a folder automatically and get the x, y, z coordinates?

import os
import cv2
import mediapipe as mp
import time
from os import listdir
import matplotlib.pyplot as plt
from pathlib import Path
import glob
import numpy
path = glob.glob("")
for file in path:
    img = cv2.imread(file)
    mpDraw = mp.solutions.drawing_utils
    mpFaceMesh = mp.solutions.face_mesh
    facemesh = mpFaceMesh.FaceMesh(max_num_faces=1)
    drawSpec = mpDraw.DrawingSpec(thickness=1, circle_radius=2)
    rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    result = facemesh.process(rgb_image)
    if result.multi_face_landmarks:
        for faceLms in result.multi_face_landmarks:
            mpDraw.draw_landmarks(img, faceLms, mpFaceMesh.FACEMESH_CONTOURS,
            drawSpec, drawSpec)
            for lm in faceLms.landmark:
                print(lm)
    cv2.imshow("image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

CodePudding user response:

A program like

import glob

import cv2
import mediapipe as mp

facemesh = mp.solutions.face_mesh.FaceMesh(max_num_faces=1)
for file in glob.glob(...):
    img = cv2.imread(file)
    rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    result = facemesh.process(rgb_image)
    for i, faceLms in enumerate(result.multi_face_landmarks):
        for j, lm in enumerate(faceLms.landmark):
            print(file, i, j, lm)

should print out each file's respective landmarks to the standard output.

You could redirect that output using your shell (python script.py > foo.txt) or come up with a more elegant output format that suits your purposes.

CodePudding user response:

If I understand well, the code is working well, but you don't want to have to see all images pop on your screen and go from one to the next one each time: just remove cv2 viewer steps :

    cv2.imshow("image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

and it should do as actually without opening each image

  • Related