读取文件夹中的多个图像

2024-05-29 03:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试读取文件夹上的多个图像并进行一些处理。我有一个提取面部地标坐标的代码。但我只能将此代码应用于一个图像。我希望脚本能处理文件夹中的所有图像。我读过一些解决方案,但它们对我不起作用。你能告诉我怎样才能给这个应用循环吗?你知道吗

这是我的密码:

import numpy as np  
import cv2
import dlib
import os
from glob import glob

mouth_matrice= open("C:/Users/faruk/Desktop/matrices/mouth.txt","w")  
lefteye_matrice= open("C:/Users/faruk/Desktop/matrices/lefteye.txt","w")
righteye_matrice= open("C:/Users/faruk/Desktop/matrices/righteye.txt","w")  
cascPath = ("C:/opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_default.xml")
all_matrice= open("C:/Users/faruk/Desktop/matrices/all.txt","w")
#imagePath = ("C:/Users/faruk/Desktop/Dataset/Testing/342_spontaneous_smile_4 (2-17-2018 8-37-58 PM)/342_spontaneous_smile_4 357.jpg") 
mypath=os.path.join("c:", os.sep, "Users", "faruk", "Desktop", "Dataset","Testing2")



PREDICTOR_PATH = ("C:/Users/faruk/Desktop/Working projects/facial-landmarks/shape_predictor_68_face_landmarks.dat")

JAWLINE_POINTS = list(range(0, 17))  
RIGHT_EYEBROW_POINTS = list(range(17, 22))  
LEFT_EYEBROW_POINTS = list(range(22, 27))  
NOSE_POINTS = list(range(27, 36))  

#RIGHT_EYE_POINTS = list(range(36, 42))
RIGHT_EYE_POINTS = list([36,39]) 
ALL_POINTS= list([36,39,42,45,48,51,54,57])
##LEFT_EYE_POINTS = list(range(42, 48))
LEFT_EYE_POINTS = list([42, 45])
##MOUTH_OUTLINE_POINTS = list(range(48, 61))
MOUTH_OUTLINE_POINTS = list([48,51,54,57])

MOUTH_INNER_POINTS = list(range(61, 68))  

 # Create the haar cascade  
faceCascade = cv2.CascadeClassifier(cascPath)  

predictor = dlib.shape_predictor(PREDICTOR_PATH)  

 # Read the image  
cv2.namedWindow('Landmarks found',cv2.WINDOW_NORMAL)
cv2.resizeWindow('Landmarks found', 800,800)
image = cv2.imread(imagePath)  
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  

 # Detect faces in the image  
faces = faceCascade.detectMultiScale(  
   gray,  
   scaleFactor=1.05,  
   minNeighbors=5,  
   minSize=(100, 100),  
   flags=cv2.CASCADE_SCALE_IMAGE  
 )  

print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:  
   cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)  

   # Converting the OpenCV rectangle coordinates to Dlib rectangle  
   dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))  

   landmarks = np.matrix([[p.x, p.y]  
               for p in predictor(image, dlib_rect).parts()])  


   #landmarks_display = landmarks[LEFT_EYE_POINTS]
   landmarks_display = np.matrix(landmarks[ALL_POINTS])



   for idx, point in enumerate(landmarks_display):  
     pos = (point[0, 0], point[0, 1])

     cv2.circle(image, pos, 2, color=(0, 255, 255), thickness=-1)


np.savetxt(all_matrice,landmarks_display,fmt='%.f',newline=',')
all_matrice.close()  
 # Draw a rectangle around the faces  
cv2.imshow("Landmarks found", image)
cv2.waitKey(0)  

Tags: theimageimportrangecv2userspointslist
1条回答
网友
1楼 · 发布于 2024-05-29 03:45:29

您可以使用这样的方法来获取目录中所有图像的路径:

import os

#  Folder with images
directory = 'c:/users/username/path/'

for filename in os.listdir(directory):
    if filename.endswith(".jpg"): 
        image_path = os.path.join(directory, filename)
        # Your code
        continue
    else:
        continue

您需要添加代码并处理每个路径。 希望这有帮助。你知道吗

编辑:

我没有办法测试它,它当然需要清理,但可能只是工作。不知道你想包括什么图像扩展,所以我只包括jpg。你知道吗

import os
import numpy as np  
import cv2
import dlib


# Chage directory path to the path of your image folder
directory = 'c:/users/admin/desktop/' 

mouth_matrice= open("C:/Users/faruk/Desktop/matrices/mouth.txt","w")  
lefteye_matrice= open("C:/Users/faruk/Desktop/matrices/lefteye.txt","w")
righteye_matrice= open("C:/Users/faruk/Desktop/matrices/righteye.txt","w")  
cascPath = ("C:/opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_default.xml")
all_matrice= open("C:/Users/faruk/Desktop/matrices/all.txt","w")

mypath=os.path.join("c:", os.sep, "Users", "faruk", "Desktop", "Dataset","Testing2")

PREDICTOR_PATH = ("C:/Users/faruk/Desktop/Working projects/facial-landmarks/shape_predictor_68_face_landmarks.dat")

JAWLINE_POINTS = list(range(0, 17))  
RIGHT_EYEBROW_POINTS = list(range(17, 22))  
LEFT_EYEBROW_POINTS = list(range(22, 27))  
NOSE_POINTS = list(range(27, 36))  

#RIGHT_EYE_POINTS = list(range(36, 42))
RIGHT_EYE_POINTS = list([36,39]) 
ALL_POINTS= list([36,39,42,45,48,51,54,57])
##LEFT_EYE_POINTS = list(range(42, 48))
LEFT_EYE_POINTS = list([42, 45])
##MOUTH_OUTLINE_POINTS = list(range(48, 61))
MOUTH_OUTLINE_POINTS = list([48,51,54,57])

MOUTH_INNER_POINTS = list(range(61, 68))  

# Create the haar cascade  
faceCascade = cv2.CascadeClassifier(cascPath)  

predictor = dlib.shape_predictor(PREDICTOR_PATH)  

for filename in os.listdir(directory):
    if filename.endswith(".jpg"): 
        imagePath=os.path.join(directory, filename)

        cv2.namedWindow('Landmarks found',cv2.WINDOW_NORMAL)
        cv2.resizeWindow('Landmarks found', 800,800)
        image = cv2.imread(imagePath)  
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  

        # Detect faces in the image  
        faces = faceCascade.detectMultiScale(gray,  
                                            scaleFactor=1.05,  
                                            minNeighbors=5,
                                            minSize=(100, 100),  
                                            flags=cv2.CASCADE_SCALE_IMAGE  
                                            )  

        print("Found {0} faces!".format(len(faces)))
        for (x, y, w, h) in faces:  
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)  

        # Converting the OpenCV rectangle coordinates to Dlib rectangle  
        dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))  

        landmarks = np.matrix([[p.x, p.y] for p in predictor(image, dlib_rect).parts()])  


        #landmarks_display = landmarks[LEFT_EYE_POINTS]
        landmarks_display = np.matrix(landmarks[ALL_POINTS])



        for idx, point in enumerate(landmarks_display):  
            pos = (point[0, 0], point[0, 1])

        cv2.circle(image, pos, 2, color=(0, 255, 255), thickness=-1)


        np.savetxt(all_matrice,landmarks_display,fmt='%.f',newline=',')
        all_matrice.close()  
        # Draw a rectangle around the faces  
        cv2.imshow("Landmarks found", image)
        cv2.waitKey(0)  
        continue
    else:
        continue

另外,在你尝试处理诸如人脸识别或图像处理之类的事情之前,你应该尝试学习一些基本的编程概念。你知道吗

相关问题 更多 >

    热门问题