Reputation: 11
Here is part of my code that has the if elif statement. For some reason the code outputs the if statement when called but ignores the elif when called. Please help:
if cv2.waitKey(1) == 32: # 32 is also equal to spacebar.
break
elif cv2.waitKey(1) == 27: # 27 is equal to escape
name = input("Name the file:")
testimage = ("'%s'.jpg".format(img_counter) %name)
cv2.imwrite(testimage, frame)
print("Picture saved!")
img_counter += 1
choice = input("Do you want to post to facebook?(Y/n)")
if choice == 'Y':
print("Posting now!")
elif choice == 'n':
print("Ok not posting.")
Upvotes: 1
Views: 136
Reputation: 95
When the key is pressed, you have one opportunity to capture its value. As written, you are attempting to "live-read" the keypress in the context of the if block. The problem is that once the condition is evaluated, the keypress is over and the if block is exited. It will never reach the elif section. Consider capturing the value in a variable (as Jim Lewis recommended in the comments), then test that variable's value.
Concerning your code sample, there is nothing occurring when 32 is true. Is this just an incomplete code snippet to illustrate your issue? If so disregard. Otherwise, you could probably write it as follows:
keyPressed = cv2.waitKey(1)
if keyPressed == 27:
name = input("Name the file:")
testimage = ("'%s'.jpg".format(img_counter) %name)
cv2.imwrite(testimage, frame)
print("Picture saved!")
img_counter += 1
choice = input("Do you want to post to facebook? (Y/n)")
if choice == 'Y':
print("Posting now!")
else:
print("Ok not posting.")
Upvotes: 1