我试图遍历其中包含图像的目录。该目录中有45张图像,但是当我执行该文件时,程序只给了我一张图像,然后它立即停止了循环。我不知道我做错了什么,也尝试过两个循环,一个在注释内,另一个在命令外。
我的代码
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
答案 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)
可能会显示问题。
答案 1 :(得分:0)
您注释掉的代码可以正常工作。只需将i = 0语句移到循环外即可(因为它每次都会将其重新分配为0),它应该可以工作。