How to save cropped images?

Viewed 12

I want to save cropped images in a new folder with the same name. I have tried this code, the code extract faces but there is no saved images in the folder. thank you.

image_path = glob.glob('/content/drive/MyDrive/ID01/')

def extract_face_from_image(image_path, required_size=(224, 224)):
  face_images = []
  for filename in os.listdir(image_path):
    for img in filename:
        image = cv2.imread(os.path.join(image_path, filename))
        face_images.append(image)
        detector = MTCNN()
        faces = detector.detect_faces(image)
  for face in faces:
# extract the bounding box from the requested face
    x1, y1, width, height = face['box']
    x2, y2 = x1 + width, y1 + height

    # extract the face
    face_boundary = image[y1:y2, x1:x2]

    # resize pixels to the model size
    face_image = Image.fromarray(face_boundary)
    face_image = face_image.resize(required_size)
    face_array = asarray(face_image)
    face_images.append(face_array)
    cv2.imwrite(os.path.join('/content/drive/MyDrive/out/'),str(face), extracted_face)
extracted_face = extract_face_from_image('/content/drive/MyDrive/ID01/')
# cv2.imwrite(os.path.join('/content/drive/MyDrive/out'),str(face), extracted_face)
1 Answers

Your os.path.join call has a typo in it. You accidentally put a closing parenthesis after '/content/drive/MyDrive/out/'. Also, you have extracted_face inside the function where you're getting extracted_face. I think you meant to use face_image instead. That line should probably read:

cv2.imwrite(os.path.join('/content/drive/MyDrive/out/', str(face)), face_image)

Lastly, don't forget to return something from extract_face_from_image(), or else extracted_face will just be None.

Related