2017-08-03 7 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ディレクトリのすべての顔を保存するにはどうすればよいですか?あなたの画像を保存する際に、単純にそのディレクトリを指定して、特定の出力ディレクトリに保存するには

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

test_inputをループし

答えて

2

は、glob.globに渡された文字列を変更します。パスを安全に結合するにはos.path.joinを使用してください。

import os 
cv2.imwrite(os.path.join("test_output", "cropped_{1}_{0}".format(str(file),str(x))), image) 
関連する問題