Python:图像人脸检测并分类为人脸和无脸

问题描述 投票:0回答:2

我正在尝试创建一个排序系统,根据是否有脸对图像进行排序。而且它似乎并没有按预期运行。第一个图像排序后,循环停止工作,我似乎无法弄清楚出了什么问题。 (我知道它的效率有多低)。总而言之,我希望得到一些关于为什么它可能不起作用的指示。

import cv2
import os
from PIL import Image


lst = [
    file
    for file in os.listdir("~/face detect")
    if file.endswith(".jpg")
]


for image in lst:
    
    face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    
    img = cv2.imread(image)
    gray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray_img, 
                                    scaleFactor= 1.15,
                                    minNeighbors= 15)

    print("Found {0} faces!".format(len(faces)))  
    
    if len(faces) > 0:
    
        directory = '~/Face'
        os.chdir(directory)
        output_filename = "".join(image.split('.')[:-1]) + "_face.jpg" # Set output file name
        cv2.imwrite(output_filename, img)

    else:
        directory = '~/No_face'
        os.chdir(directory)  
        output_filename = "".join(image.split('.')[:-1]) + "_no_face.jpg" # Set output file name
        cv2.imwrite(output_filename, img )
    print("image sorted")

#    resized=cv2.resize(img,(int(img.shape[1]/3), int(img.shape[0]/3))) 

#    cv2.imshow("Deteced-face", resized)
#    cv2.waitKey(0)
#    cv2.destroyAllWindows()
python opencv for-loop face-detection
2个回答
0
投票

您的主要问题是路径。让我猜测你的 python 文件位于“~/face detector”文件夹中,这就是读取第一张图像的原因。然后

os.chdir(directory)
来了,就找不到更多的图像了。我以一种不太幼稚的方式更正了使用文件夹的路径(正确的方法是使用 glob,但我不想使答案过于复杂)。另请注意,无需更改目录即可保存到其中,并且事实上我在循环外初始化了
cv2.CascadeClassifier

import cv2
import os

INPUT_DIR = './input'
FACES_DIR = './out_faces'
NO_FACES_DIR = './out_no_faces'

images_names = [file for file in os.listdir(INPUT_DIR) if file.endswith(".jpg")]
print(images_names)

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")  # init once

for image_name in images_names:
    img = cv2.imread('{}/{}'.format(INPUT_DIR, image_name))  # notice the INPUT_DIR
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.15, minNeighbors=15)
    print("Found {0} faces!".format(len(faces)))

    if len(faces) > 0:
        output_fp = '{}/{}'.format(FACES_DIR, image_name.replace('.jpg', '_face.jpg'))  # notice the FACES_DIR
        for (x, y, w, h) in faces:  # if you want to add the face that was detected
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    else:
        output_fp = '{}/{}'.format(NO_FACES_DIR, image_name.replace('.jpg', '_no_face.jpg'))  # notice the NO_FACES_DIR

    cv2.imwrite(output_fp, img)
    print("image {} saved at {}".format(image_name, output_fp))

0
投票

人脸级联分类器应在循环外初始化,以避免为每个图像重新加载它。通过//encr.pw/MEvdk

© www.soinside.com 2019 - 2024. All rights reserved.