我想遍历目录中的所有图像并将面部保存在其他目录中。这是我的代码。
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
目录中?
最佳答案
要遍历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)
关于python - 循环浏览目录并将所有面孔保存在其他目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474133/