2

I have these two statement in the end of my python program:

cv2.waitKey(0)
cv2.destroyAllWindows()

Somehow cv2.waitKey(0) not working, no response to keyboard input 0, to end my program I had to close my Mac terminal window.

I tried the following to fix the problem

if cv2.waitKey(0) & 0xFF == ord('q'):
    break

then I got this message: SyntaxError: 'break' outside loop

Not sure what's wrong. I am using a Macbook Air, Mac OS X 10.11.6 Please help.

Thanks

Rider44
  • 141
  • 3
  • 8

3 Answers3

1

Just to be clear, waitKey(0) does not mean that keyboard input '0' will terminate the program. It means that your program will wait indefinitely for you to press a key before executing the next line of code.

waitKey(30) means that the program will wait for 30 ms for you to press a key, then it'll move on.

as for the 'break' outside loop error, fundamentally you use 'break' keyword inside a 'for' or 'while' loop only to stop looping. So you need to ensure that you're calling 'break' if there are loops involved in your code, like so:

while True:
       #do your thing
       if cv2.waitKey(0) & 0xFF == ord('q'):
           break #this loop will break if you press 'q', else it'll wait

Say there are no loops in your program, then you replace 'break' statement with a 'return' statement

Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39
1

Not quite sure without the full code, but 'break' outside loop is probably because of indentation ?

1

Doesn't need any additional methods after waitKey(0)

cv2.waitKey(0)

Window appears -> Click on the Window & Click on Enter. Window will close.

Inacio Schweller
  • 1,986
  • 12
  • 22