0

I made a program that reads pixels from a camera. I have used a while loop. But I can't close the program from terminal without pressing 'Cltrl + C'. I want to close the program using ESC button ( ASCII 27). I tried the following code, which is not working. Any help would be appreciated

import cv2 as cv
import numpy as np

cap = cv2.VideoCapture(0)

while True:
   _, frame = cap.read()

   redimage = frame[:,:,2]
   print(redimage)

   k = cv.waitKey(1) & 0xFF
   if k == 27:
      break

2 Answers2

0

Use:

if k == chr(27):
   break
rahul mehra
  • 418
  • 2
  • 13
0

cv.waitKey(1) is working for opencv gui only. You can't capture keyboard events in console with this function.

So, you can change your code to show the frame that you are reading from the camera.

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
   _, frame = cap.read()
   redimage = frame[:,:,2]
   cv2.imshow('frame', frame)
   print(redimage)
   k = cv2.waitKey(1) & 0xFF
   if k == 27:
      break

cap.release()
cv2.destroyAllWindows()

You can find in this answer a way to capture keyboard events in console.

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67