Skip to content

Instantly share code, notes, and snippets.

@imneonizer
Created May 2, 2021 10:36
Show Gist options
  • Save imneonizer/56ddd8de8a417c0d0c74df4dfd97266c to your computer and use it in GitHub Desktop.
Save imneonizer/56ddd8de8a417c0d0c74df4dfd97266c to your computer and use it in GitHub Desktop.
Custom waitKey for opencv
# make sure terminal window is active when pressing any key
import cv2
import numpy as np
import time
from waitKey import waitKey
frame = np.zeros((300, 300, 3))
idx, st = 0, time.time()
while True:
cv2.imshow("frame", frame)
key = waitKey()
if key == 's':
cv2.imwrite("frame.jpg", frame)
elif key == 'q':
break
# https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-a-script-from-the-termina
import sys
import select
import termios
import cv2
class waitKey():
def __init__(self):
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgetattr(self.fd)
# New terminal setting unbuffered
self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)
def __del__(self):
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def __call__(self):
cv2.waitKey(1)
dr,dw,de = select.select([sys.stdin], [], [], 0)
if not dr == []:
return sys.stdin.read(1)
return ''
waitKey = waitKey()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment