How to use waitkey with VideoCapture()

Hi,
I am struggling about this example. I’d like to update the frame window wrt key press, e.g. display grayscale image when I press ‘c’ on the keyboard, but this does not work:
My codes:

import numpy as np
import cv2 
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame', frame)
    key = 0xFF & cv2.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('c'):
        print('pressed c')
        cv2.imshow('frame', gray)
        
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Your question related to general programming skill
Try the following code.

import numpy as np
import cv2 
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()

convert_to_gray = False
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    if convert_to_gray:
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame', frame)
    key = 0xFF & cv2.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('c'):
        convert_to_gray = not convert_to_gray # Toggle convert_to_gray value
        
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
1 Like

Thank you.
I found that I had issues while using several waitkeys for the same window.
Best