Automated img. dataset cropping of safety helmet faces and heads

83 Views Asked by At

I am currently trying to run this code on a dataset which includes multiple full-bodied photos of people with hardhats.

Here is the code:

def detect_face(img):
    heregray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.7, minNeighbors=5)
    return faces

filename = ("C:\\Users\Vitaliy Yashchenko\\Desktop\\OpenCV Face recognition\\!!!\\dataset\\hattocrop")

for img in glob.glob(filename+'/*.*'):
    var_img = cv2.imread(img)

    face = detect_face(var_img)
    print(face)
    if (len(face) == 0):
        continue
    for(ex, ey, ew, eh) in face:
        crop_image = var_img[ey:eh+ey, ex:ex+ew]
        cv2.imshow("cropped", crop_image)
        cv2.waitKey(0)  
        cv2.imwrite(os.path.join("outputs/",str(img)),crop_image)

As the haarcascade recognizes only the face, I tried to crop the face with the hard hat and I was slightly confused with the axes ex, ey, ew, eh.

If I run the following in the corresponding line:

crop_image = var_img[ey:eh+ey+100, ex:ex+ew]

I get the lower part of the face.

What is the approriate way to define the higher part of the face(head) in the cropped img so the cropped one will include the safety hard hat?

1

There are 1 best solutions below

0
Maciek Woźniak On

I am not sure what is the issue but:

  • dimensions in CV images and basically in computer vision are read from the top left corner (0,0) to the bottom right corner (img_width,img_height)
  • cv2 has some deep learning tools built-in but if you are really interested in the project you should use other tools such as PyTorch, you can also use the models trained there in OpenCV
  • last tip (side note) - don't put spaces in your directories names :)