2017-08-03 33 views
0

我想遍歷目錄中的所有圖像並將面保存在其他目錄中。這是我的代碼。在目錄中循環並將所有面保存在其他目錄中

cascPath = "haarcascade_frontalface_alt2.xml" 

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

import glob 
files=glob.glob("*.jpg") 
for file in files: 

    # Read the image 
    image = cv2.imread(file) 
    print(file) 
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 

    # Detect faces in the image 
    faces = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=4, 
     minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE) 
    print ("Found {0} faces!".format(len(faces))) 

    # Crop Padding 
    left = 10 
    right = 10 
    top = 10 
    bottom = 10 

    # Draw a rectangle around the faces 
    for (x, y, w, h) in faces: 
     print (x, y, w, h) 

     image = image[y-top:y+h+bottom, x-left:x+w+right] 

     print ("cropped_{1}{0}".format(str(file),str(x))) 
     cv2.imwrite("cropped_{1}_{0}".format(str(file),str(x)), image) 

上述代碼預計圖像爲jpg格式。它還從根文件夾中檢索圖像並保存在根文件夾本身中。 如何通過test_input目錄循環並保存test_output目錄中的所有面?

回答

2

要遍歷test_input,修改傳遞到glob.glob字符串:

files = glob.glob("test_input/*.jpg") 

要保存到特定的輸出目錄只是保存圖像時指定該目錄。使用os.path.join可安全地加入路徑。

import os 
cv2.imwrite(os.path.join("test_output", "cropped_{1}_{0}".format(str(file),str(x))), image)