[Python] Cut faces in order, not randomly

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I created a Python code that recognizes and crops faces. But the problem is that it crops the faces randomly and not in the order in the original image that contains all the faces. What is required please: is that the code crops the faces in order from the top to the right until it reaches the last face.

    Please put the code with a folder named (Input Images) that contains the image that contains the collected faces. And create a folder named Output Images that stores the cropped faces.. With the face recognition xml file haarcascade_frontalface_default.xml text

    The Code:

    import os
    import cv2
    import numpy as np
    import os, os.path
    # Load the cascade classifier
    #download this here https://raw.githubusercontent.com/opencv/opencv/4.x/data/haarcascades/haarcascade_frontalface_default.xml just go there and ctrl + s
    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")


    #rename a file
    #for dirname in os.listdir("."):
    # if os.path.isdir(dirname):
    # for i, filename in enumerate(os.listdir(dirname)):
    # os.rename(dirname + "/" + filename, dirname + "/" + str(i) + ".jpg")

    # Read the input image
    img = cv2.imread("Input Images/image.jpg")
    #let's double the size of our image
    img_double=cv2.resize(img,None,fx=1,fy=1,interpolation=cv2.INTER_CUBIC)
    # let's do the resizing by exact dimensions
    image_resize=cv2.resize(img,(600,700),interpolation=cv2.INTER_AREA)


    # Convert into grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Detect faces
    faces = face_cascade.detectMultiScale( gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(150, 150), )


    # loop over all detected faces
    if len(faces) > 0:
    for i, (x,y,w,h) in enumerate(faces):


    #face = img[y:y+h, x:x+w]
    face = img[y-65:y+h+40,x-40:x+w+55]


    # cv2.imshow(f"Cropped Face {i}", face)

    cv2.imwrite("Output Images/" f'0{i}.jpg', face)
    print(f"0{i}.jpg is saved")


    # concatenate image Vertically
    #Verti = np.concatenate((img, img), axis=0)

    # Number of all detected faces
    print("[INFO] Found {0} Faces.".format(len(faces)))


    # display the image with detected faces
    cv2.imshow('scaling_exact',image_resize)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


    Original image illustrative example

    What is required please: is that the code crops the faces in order from the top to the right until it reaches the last face. example

    [Original image] (https://i.sstatic.net/mdTMAMpD.jpg)

    Continue reading...

Compartilhe esta Página