简体   繁体   English

Python输出会重复,即使它会中断

[英]Python output repeats even though it should break

I have a script that is using OpenCV to find faces and if a face is not found it outputs "No faces found" but it never does anything else. 我有一个使用OpenCV查找面孔的脚本,如果未找到面孔,它将输出“未找到面孔”,但它从不做任何其他事情。 It should look back up and ask for another image. 它应该备份并要求其他图像。 Can anyone tell me why it just prints "No faces found" until I press CTRL+C? 谁能告诉我为什么在我按CTRL + C之前只打印“找不到面孔”?

def Crop(
    imagePattern,
    boxScale,
    outputimg,
    padding,
    ):
    happy = True
    imgList = glob.glob(imagePattern)
    while happy:
        if len(imgList) <= 0:
            return
        else:
            for img in imgList:
                pil_im = Image.open(img)
                cv_im = pil2cvGrey(pil_im)
                faces = DetectFace(cv_im, faceCascade)
                if faces:
                    n = 1
                    for face in faces:
                        croppedImage = imgCrop(pil_im, face[0],
                                padding, boxScale=boxScale)
                        (fname, ext) = os.path.splitext(img)
                        fname = os.path.basename(fname)
                        croppedImage.save(outputimg + '\\' + fname
                                + ' -c' + ext)
                        n += 1
                    print 'Cropping:', fname
                else:
                    print 'No faces found:', img
                    break

                            # Verify image
                            # savedPath = outputimg + '\\' + fname + ' -c' + ext
                            # verify = cv2.imread(savedPath, 0)
                            # cv2.imshow('Saved Image', verify)

                print 'Please open the file manually to view for now'
                print 'Are you happy with the final crop?'
                happyTest = raw_input('Enter y or n: ')
                happyTest = happyTest.strip()
                if happyTest == 'y':
                    happy = False
                elif happyTest == 'n':
                    padding = int(raw_input('Enter crop padding:'))
                else:
                    print 'Not a valid input'
    print 'Do you have more pictures to take?'
    again = raw_input('Enter y or n: ')
    if again == 'y':
        Webcam(webcam, padding, boxScale)
    else:
        print 'Closing application'
        time.sleep(3)
        raise SystemExit

Sorry for the confusion, I had a bad copy/paste due to me using tabs for my code. 很抱歉造成混淆,由于使用代码标签,我的复制/粘贴错误。

EDIT: Thank you for letting me know about the mixing tabs and spaces but my issue is still the same. 编辑:谢谢您让我知道有关混合选项卡和空格,但我的问题仍然是相同的。 It also does not matter if I use a break or a continue. 使用中断还是继续也没关系。 Do I need to use recursion and call the function again? 我是否需要使用递归并再次调用该函数?

You are using a break statement, which halts the for loop completely. 您正在使用break语句,该语句完全停止for循环。

Instead, use a continue statement there to skip the current image and move on to the next one within the for loop. 相反,请在该处使用continue语句跳过当前图像,然后继续前进至for循环中的下一个图像。

Read more about break and continue here 了解更多关于break在此处 continue

Also, You are using tabs and spaces togather, which is causing the indentation of the blocks to be misaligned. 另外,您正在使用制表符和空格聚集,这会导致块的缩进未对齐。 While they look as if they are aligned all right, you will have nightmares debugging tab errors, so just change your editor settings to use a tab as 4 whitespaces. 尽管它们看起来好像完全对齐,但是您将遇到噩梦,调试选项卡错误,因此只需更改编辑器设置以将选项卡用作4个空格即可。

EDIT 编辑

There are multiple issues in your code: 您的代码中存在多个问题:

  1. You are checking for len(imgList)<=0 which is redundant as has already been pointed out in other answer. 您正在检查len(imgList)<=0 ,这是多余的,正如其他答案中已经指出的那样。
  2. The happytest value that you take is taken for every img in imglist, yet only the one entered on the last run will affect the value of the happy variable. 您为imglist中的每个img都采用了happytest值,但是只有最后一次运行时输入的值才会影响happy变量的值。
  3. Because of #2 above, I am inclined to think that your original intent was to stop at any run during which the value of happy was False , which is definitely not happening right now. 由于上面的#2,我倾向于认为您的最初意图是在happy值为False任何运行中停止,这绝对不会在现在发生。
  4. You are using capital letters and camel case both to begin the name of some functions and I am having a hard time figuring if something is a public class or another function. 您正在使用大写字母和驼峰大小写来开始某些功能的名称,而我很难确定是公共类还是其他功能。
  5. There are multiple external functions being referenced within the code, but I have not much clue of what they are supposed to do, and whether they actually do whatever they are supposed to do. 在代码中引用了多个外部函数,但是我对它们应该做什么以及它们是否实际执行了应做的事情并不了解。

I don't know if this is the problem, but it is how you posted it anyway: Your commands after the else statement are not indented. 我不知道这是否是问题,但无论如何是您发布它的方式:else语句后的命令不缩进。 Shouldn't it have given you an error? 它不应该给您一个错误吗?

You have an extar break on your code -this version should work: 您的代码break了-此版本应该可以运行:

for img in imgList:
    pil_im=Image.open(img)
    cv_im=pil2cvGrey(pil_im)
    faces=DetectFace(cv_im,faceCascade)
    if faces:
        n=1
        for face in faces:
            croppedImage=imgCrop(pil_im, face[0], padding, boxScale=boxScale)
            fname,ext=os.path.splitext(img)
            fname = os.path.basename(fname)
            croppedImage.save(outputimg + '\\' + fname + ' -c' + ext)
            n+=1
        print 'Cropping:', fname
    else:
        print 'No faces found:', img

So, while it is true on the other answers and comments that you shpould not have the "break" inside the else statement - the problem you put forward in your question happens because you have that break at all: if the code reach that else block, it will just break out of the for img in imgList: loop and process nothing further. 因此,尽管在其他答案和注释上确实是您在else语句中没有“中断”的else ,但是您在问题中提出的问题却是因为您完全中断了:如果代码到达了else块,它只会脱离for img in imgList:循环中的for img in imgList:进行任何处理。

besides that, I have fixed two other things in this code: indentation - in Python it is serious business, not "what works is fine". 除此之外,我还修复了此代码中的其他两件事:缩进-在Python中这是严肃的事情,而不是“行之有效”。 The recomendation is to use 4 spaces per block nesting - no more, no less, and never, never mix tabs and spaces. 建议每个块嵌套使用4个空格-不要多也不要少,并且永远不要将制表符和空格混合使用。 You have to configure that on your code editor preferences. 您必须在代码编辑器首选项上进行配置。

The other part of your code that is alien to Python is the verification prior to the loop if len(imgList)<=0: that is complettly superfluous in Python (not to mention the <= part): if the list lenght is zero (it can't be negative), the for statement will try to pick the first item, and since it does not exist, the program will simply continue after the for block. 代码的另一部分与Python if len(imgList)<=0:则在循环之前进行验证if len(imgList)<=0:在Python中完全多余(更不用说<=部分):如果列表长度为零( (不能为负), for语句将尝试选择第一个项目,由于它不存在,因此该程序将在for块之后继续执行。 Each level of indentation you reduce in your code is a bonus in readability. 您在代码中减少的每个缩进级别都提高了可读性。 (The Zen of Python even reads "Flat is better than nested"). (Python的Zen甚至读到“ Flat比嵌套更好”)。 On the other hand, if in some other part of the code you really have to check if the lsit is empty,just do if imgList: , as sequences in Python have the nice property of having a False boolean value if they are empty, and True otherwise. 另一方面,如果您确实需要检查代码的其他部分,则lsit是否为空,只需检查imgList:, if imgList:中的序列具有很好的属性,如果它们为空,则具有False布尔值;以及否则为True

The break you have coded breaks out of the for img in imgList: loop, not the while happy: loop. break已经编写跳出的for img in imgList:循环,而不是 while happy:循环。 And since the code you use to ask the user if the cropping is satisfactory, is inside that loop (and after the break ), it never gets reached (and thus happy can never be set False ). 而且,由于你的代码用来询问用户是否裁剪是令人满意的,是循环(与后内break ),它永远不会被达成(并因此happy永远不能设置False )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM