[英]I can't loop through a directory which has images
我試圖遍歷一個里面有圖像的目錄。 該目錄中有 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
您在循環中繼續設置i = 0
,從而繼續覆蓋 output 文件。 而是做
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)
會顯示問題。
您注釋掉的代碼工作正常。 只需將 i = 0 語句移到循環外(因為它每次都將其重新分配為 0),它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.