VideoCapture connects an OpenCV program to a camera so it can retrieve images one frame at a time. Open the default camera with cv2.VideoCapture(0), then verify that initialization succeeded before starting work. This makes camera access a small, reusable part of an interactive robotics application. section 8.3.1 section 8.3.3
A practical capture cycle is:
- Create a capture object for the default camera: cap = cv2.VideoCapture(0). section 8.3.1
- Check cap.isOpened() before continuing; a failed check means the camera was not initialized correctly. section 8.3.1
- Call cap.read() to grab and decode the next frame. It returns a success Boolean and the image. section 8.3.1
- Use the returned Boolean to stop or report an error when a frame cannot be read. section 8.3.3
- Call cap.release() when the application exits to close the camera. section 8.3.1 section 8.3.3
A captured frame is a NumPy ndarray. For a 640-by-480 color image, shape is (480, 640, 3): height comes first, then width, followed by three color components. The frame can be saved directly with cv2.imwrite() or passed to display and drawing functions. section 8.3.1 section 8.3.3
Space-key snapshot preview
Keep reading frames in an event loop while cv2.waitKey(1) handles GUI events. When the space key is pressed, save the current frame with a timestamped filename and display a short “saving photo...” message; quit with Q or Escape. Assertions make failures to open the camera or read a frame explicit. section 8.3.3
Listing 8.2 snapshot.py: Taking a snapshot when the space key is pressed
#!/usr/bin/env python3
from datetime import datetime
import cv2
ESC_KEY = 27
BLUE = (255, 0, 0)
FONT = cv2.FONT_HERSHEY_SIMPLEX
TEXT_POS = (10, 30)
MSG_FRAME_COUNT = 10
def save_photo(frame):
stamp = datetime.now().isoformat().replace(':', '.')
cv2.imwrite(f'photo_{stamp}.jpg', frame)
def show_image(frame, messages):
if messages:
cv2.putText(frame, messages.pop(), TEXT_POS, FONT, 1, BLUE)
cv2.imshow('preview', frame)
def set_message(messages, text):
messages[:] = [text] * MSG_FRAME_COUNT
def main():
cap = cv2.VideoCapture(0)
assert cap.isOpened(), 'Cannot open camera'
messages = []
while (key := cv2.waitKey(1)) not in [ord('q'), ESC_KEY]:
ret, frame = cap.read()
assert ret, 'Cannot read frame from camera'
if key == ord(' '):
save_photo(frame)
set_message(messages, 'saving photo...')
show_image(frame, messages)
cap.release()
if __name__ == "__main__":
main()
This complete snapshot program combines VideoCapture setup, per-frame reads, keyboard handling, image saving, preview display, and release cleanup. section 8.3.3
