Home>

I wanted to do image recognition with tensorflow, so I thought about making a program that cuts out only the face.
I ran the program by referring to this site (https://newtechnologylifestyle.net/opencv_face_trimingu/).
On this site, it was a program that cuts only the face for one image, so if you cut all the images in the file, the program will be
I modified it, but it is an error and I do not understand the problem.
I'm sorry, but I would like to ask for your help.

Source code
import cv2
import glob
directory ='D: /program/face/*.jpg' // File with face image
path ='D:/program/facecut /'// Output destination file
HAAR_FILE ='face.xml'
cascade = cv2.CascadeClassifier (HAAR_FILE)
c = 0
for image_picture in glob.glob ('./face/*.jpg'):
    img = cv2.imread (image_picture)
    img_g = cv2.imread (image_picture, 0)
    face = cascade.detectMultiScale (img_g)
    print (face)
    for x, y, w, h in face:
        face_cut = img [y: y + h, x: x + w]
    c + = 1
    filename = path +'face_cut {} .jpg'.format (c)
    cv2.imwrite (filename, face_cut)
Traceback (most recent call last):
  File "d: /program/OneImageFaceCut.py", line 19, in<module>
    cv2.imwrite (filename, face_cut)
NameError: name'face_cut' is not defined
What I tried
for image_picture in glob.glob ('./face/*.jpg'):
    img = cv2.imread (image_picture)
    img_g = cv2.imread (image_picture, 0)
    face = cascade.detectMultiScale (img_g)
    print (face)
    for x, y, w, h in face:
        face_cut = img [y: y + h, x: x + w]
    c + = 1
filename = path +'face_cut {} .jpg'.format (c)
cv2.imwrite (filename, face_cut)


In this way, I put out cv2.imwrite () outside the for statement. Then, the compilation passed, and only one image with the face cut out was saved.
I can imagine that only one sheet is output, but I'm not sure if it won't compile when I put it in the for statement.

Supplementary information (FW/tool version, etc.)

opencv 4.0.1

  • Answer # 1

    If no face is detected in the very first image,for x, y, w, h in face:Because the loop inside is not executedface_cutWill go to the save process without being defined.
    Therefore, an error has occurred.

    Also, after being detected even onceface_cutSince is defined, no error will occur, but the process is such that the data of another image is saved for the image for which the face is not detected.

    The easiest way to fix it isc + = 1After that, it will be put in the for block.