3. Reading Local Cameras: Mastering VideoCapture
The cv2.VideoCapture class is the heart of OpenCV's input system. Understanding its parameters is crucial for high-performance acquisition.
3.1 The Basic Loop
Here is the standard pattern for reading and displaying a camera feed. This loop handles frame grabbing and display in a synchronized manner.
import cv2
# Initialize the camera (index 0 is usually default)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open camera.")
exit()
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imshow('Live Feed', frame)
# Press 'q' to exit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
3.2 Setting Resolution and FPS
You can request specific hardware settings using cap.set(). Note that the actual values depend on what your hardware supports.
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
cap.set(cv2.CAP_PROP_FPS, 60)