读取文件夹python中的多个图像

时间:2018-03-27 20:30:22

标签: python

我正在尝试读取文件夹上的多个图像并进行一些处理。我有一个提取面部地标坐标的代码。但我可以将此代码仅应用于一个图像。我希望脚本能够处理文件夹中的所有图像。我已经阅读了一些解决方案,但它们并没有为我工作。你能告诉我如何应用循环吗?

这是我的代码:

m = MyClass()
# e.g. m.another_instance_method(3, "foo", bar=9)
m.my_instance_method(MyClass.another_instance_method, 3, "foo", bar=9)

1 个答案:

答案 0 :(得分:0)

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

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

P.s在尝试解决面部识别或图像处理之类的问题之前,您应该尝试学习基本的编程概念。