Python:Break while循环

时间:2016-12-11 23:52:05

标签: python

我正在使用一个代码来获取图像文件的输入(可以是源文件夹中的任何数字)并处理它们然后保存文件。我使用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

2 个答案:

答案 0 :(得分:2)

for imagePath in imagePaths:已遍历您的数据并处理所有内容。它没有理由嵌套在另一个循环中。删除该循环。

...
imagePaths.sort()

i = 1
for imagePath in imagePaths:
    ...

答案 1 :(得分:2)

INSERT ON DUPLICATE KEY UPDATE

在for循环结束时添加while True: for ...: // your code // your code... break // terminate while loop ,它将终止您当前的break循环

在您的情况下,您根本不需要while True。 for循环已经迭代了所有图像。