2016-12-11 15 views
-1

Я использую код, который принимает входные файлы изображений (может быть любым числом в исходной папке) и обрабатывает их, а затем сохраняет файлы. Я использую while loop для сохранения файлов. Но проблема, с которой я сталкиваюсь, заключается в том, что, когда цикл обрабатывает все изображения и сохраняет их, он начинается снова и снова. Как я могу разбить цикл, как только все изображения в исходной папке будут обработаны и сохранены?Python: Break while loop

код я использую:

# construct the argument parse and parse the arguments 
ap = argparse.ArgumentParser() 
ap.add_argument("-i", "--images", required=True, help="path to images directory") 
args = vars(ap.parse_args()) 

# initialize the HOG descriptor/person detector 
hog = cv2.HOGDescriptor() 
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) 

# loop over the image paths 
imagePaths = list(paths.list_images(args["images"])) 

#open images in a sequence 
imagePaths.sort() 

i =1 
while True: 
    for imagePath in imagePaths: 
     # load the image and resize it to (1) reduce detection time 
     # and (2) improve detection accuracy 
     image = cv2.imread(imagePath) 
     image = imutils.resize(image, width=min(700, image.shape[1])) 
     orig = image.copy() 

     # detect people in the image 
     (rects, weights) = hog.detectMultiScale(image, winStride=(4, 4), 
     padding=(8, 8), scale=1.05) 

     # draw the original bounding boxes 
     for (x, y, w, h) in rects: 
      cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2) 

     # apply non-maxima suppression to the bounding boxes using a 
     # fairly large overlap threshold to try to maintain overlapping 
     # boxes that are still people 
     rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects]) 
     pick = non_max_suppression(rects, probs=None, overlapThresh=0.65) 

     # draw the final bounding boxes 
     for (xA, yA, xB, yB) in pick: 
       cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2) 

     # show some information on the number of bounding boxes 
     filename = imagePath[imagePath.rfind("/") + 1:] 
     print("[INFO] {}: {} original boxes, {} after suppression".format(
     filename, len(rects), len(pick))) 

     cv2.imwrite('%d.png' % (i),image) 
     i +=1 
+0

Почему это в бесконечной петле while? – TigerhawkT3

+0

while True == infin – davedwards

+0

Вы можете использовать break для выхода из цикла. Однако петля здесь не имеет смысла. – Fang

ответ

2

for imagePath in imagePaths: уже перебирает данных и обрабатывает все. Нет причин для его вставки в другой цикл. Удалите этот цикл.

... 
imagePaths.sort() 

i = 1 
for imagePath in imagePaths: 
    ... 
+0

Я попытался сделать это: 'i = 1'' для imagePath в imagePaths: .... 'и я сохранил файл' cv2.imwrite ('% d.png'% (i), image) '. Он по-прежнему продолжает цикл –

+0

@NikhileshSharma - Вы уверены, что сохранили измененный скрипт? – TigerhawkT3

+0

Мой плохой сэр, все работает отлично. –

2
while True: 
    for ...: 
     // your code 
     // your code... 
    break // terminate while loop 

Добавить break в конце вашего для цикла, он будет завершить текущий цикл while True

В вас случае, вам не нужно while True вообще. Цикл for выполняет итерацию всех ваших изображений.