我无法循环浏览包含图像的目录

2024-04-19 04:09:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着循环浏览一个目录,里面有图像。该目录中有45个图像,但当我执行该文件时,程序只给了我一个图像,然后它立即停止了循环。我不知道我做错了什么,我也尝试了两个for循环,一个在注释内,另一个在命令外

我的代码

import cv2
import argparse
import os
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to not hong dataset")
ap.add_argument("-o", "--output", required=True, help="path to output directory")
args = vars(ap.parse_args())

haar_cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(haar_cascade)

print("\n[INFO] Working on image...")

"""
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    i = 0
    image = cv2.imread(imagePath)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, 
                                    minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
"""

for imagePath in os.listdir(args["dataset"]):
    i = 0
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, 
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1

Tags: pathinimageimportforoutputosargs
2条回答

注释掉的代码工作正常。只要将i=0语句移到循环之外(因为每次它都将其重新分配为0),它就应该可以工作了

在循环中不断设置i = 0,从而不断覆盖输出文件。取而代之的是

for i, imagePath in enumerate(os.listdir(args["dataset"])):
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, 
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)

调试这种事情的一般方法是在代码中添加一些打印。例如,顶部的print("input", imagePath)和底部附近的print("output", p)会显示出问题

相关问题 更多 >