📜  waitkey(1) & 0xff (1)

📅  最后修改于: 2023-12-03 15:35:39.469000             🧑  作者: Mango

Introduction to waitKey(1) & 0xff in OpenCV

In OpenCV, waitKey(1) & 0xff is a commonly used function that waits for a key event to occur and returns the key code of the pressed key. It is often used in conjunction with other OpenCV functions, such as displaying images or capturing video.

Syntax

The syntax for waitKey(1) & 0xff is as follows:

key = cv2.waitKey(1) & 0xff

The waitKey() function waits for a key event to occur for the specified number of milliseconds (1 millisecond in this case), and the bitwise AND operation with 0xff ensures that only the least significant 8 bits (i.e., the key code) are kept.

Parameters

The only parameter for waitKey() is the number of milliseconds to wait for a key event. A value of 0 means that it waits indefinitely, while a value of 1 or higher means that it waits for the specified number of milliseconds.

Usage

Here are some examples of how waitKey(1) & 0xff can be used in OpenCV:

  • Display an image and wait for a key to be pressed:
import cv2

img = cv2.imread('image.jpg')
cv2.imshow('image', img)
key = cv2.waitKey(0) & 0xff
  • Capture video from a camera and display it until the 'q' key is pressed:
import cv2

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    cv2.imshow('video', frame)
    key = cv2.waitKey(1) & 0xff
    if key == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
  • Process keyboard events in a GUI application:
import cv2
import tkinter as tk

def on_key(event):
    key = event.char & 0xff
    if key == ord('q'):
        root.destroy()

cap = cv2.VideoCapture(0)
root = tk.Tk()
root.bind('<Key>', on_key)
while True:
    ret, frame = cap.read()
    cv2.imshow('video', frame)
    root.update()
cap.release()
cv2.destroyAllWindows()
Conclusion

waitKey(1) & 0xff is a versatile function in OpenCV that is used to wait for key events and obtain their key codes. It can be used in a variety of applications, such as displaying images, capturing video, and processing keyboard events in GUI applications.