Displaying Camera Frames

OpenCV allows named windows to be created, redrawn, and destroyed using the namedWindow(), imshow(), and destroyWindow() functions. Also, any window may capture keyboard input via the waitKey() function and mouse input via the setMouseCallback() function. Let’s look at an example where we show the frames of a live camera input:

# Import OpenCV library
import cv2

# Initialise clicked to false
clicked = False
# This function change clicked variable value to true when mouse is clicked
def onMouse(event, x, y, flags, param):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True
# Create a video caputure instance
cameraCapture = cv2.VideoCapture(0)
# Create window named MyWindow
cv2.namedWindow('MyWindow')
# Set onMouse function to window
cv2.setMouseCallback('MyWindow', onMouse)
print('Showing camera feed. Click window or press any key to stop.')
# Read captured video and store them in success and frame
success, frame = cameraCapture.read()
# Loop until key is not pressed or Mouse is not clicked
while success and cv2.waitKey(1) == -1 and not clicked:
    cv2.imshow('MyWindow', frame)
    success, frame = cameraCapture.read()
# Close window.
cv2.destroyWindow('MyWindow')
# Clear cameraCapture instance
cameraCapture.release()

The argument for waitKey() is a number of milliseconds to wait for keyboard input. The return value is either -1 (meaning that no key has been pressed) or an ASCII keycode, such as 27 for Esc.

The mouse callback passed to setMouseCallback() should take five arguments, as seen in our code sample. The callback’s param argument is set as an optional third argument to setMouseCallback(). By default, it is 0. The callback’s event argument is one of the following actions:

The mouse callback’s flags argument may be some bitwise combination of the following events: