Search code examples
pythonpython-3.xdirectorysaveobject-detection

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


I'm creating a data collector program using object detection (cropped faces) but failed to save that in a 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

Solution

  • FaceFileName = '/path_to_faces_folder/faces/'+ str(y) + ".jpg"
    # save image
    face_write = cv2.imwrite(FaceFileName,f1)
    

    There may be a path problem. If it's, giving full path of faces folder may solve the problem.

    Edit:

    I am editing my answer with respect to your comment. I assume that you can get the label of your prediction for each image.

    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)