如何将从(对象检测)裁剪的检测到的面部保存到其特定创建的文件夹中?

how to save a detected face cropped from (object detection) to its particular created folder?

我正在创建一个使用对象检测(裁剪面)的数据收集器程序,但未能将其保存在特定的创建文件夹中。

for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        sub_face = fl[y:y+h, x:x+w]

        FaceFileName = 'faces/'+ str(y) + ".jpg"
        cv2.imwrite(FaceFileName, sub_face)#problem

        color = colors[i]
        cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
        cv2.putText(frame,label,(x, y + 30),cv2.FONT_HERSHEY_SIMPLEX, 1, color, 1
FaceFileName = '/path_to_faces_folder/faces/'+ str(y) + ".jpg"
# save image
face_write = cv2.imwrite(FaceFileName,f1)

可能是路径问题。如果是,提供 faces 文件夹的完整路径可能会解决问题。

编辑:

我正在根据您的评论编辑我的答案。我假设您可以获得每张图像的预测标签。

import os
predicted_class_label = "dog" # somehow you get it somewhere in your code
if os.path.isdir(predicted_class_label):
    FaceFileName = predicted_class_label +"/"+ str(y) + ".jpg"
    face_write = cv2.imwrite(FaceFileName,sub_face)
else:
    os.mkdir(predicted_class_label)
    FaceFileName = predicted_class_label +"/" + str(y) + ".jpg"
    face_write = cv2.imwrite(FaceFileName,sub_face)