| import cv2 |
| import time |
| import sys |
|
|
| def test_camera(device_id, width=640, height=480, fps=30): |
| print(f"\n=== Testing Camera Index {device_id} ===") |
| |
| |
| backend = cv2.CAP_V4L2 if hasattr(cv2, 'CAP_V4L2') else cv2.CAP_ANY |
| backend_name = "V4L2" if backend == cv2.CAP_V4L2 else "ANY" |
| print(f"Opening with backend: {backend_name}") |
|
|
| cap = cv2.VideoCapture(device_id, backend) |
| |
| if not cap.isOpened(): |
| print(f"Error: Could not open camera {device_id}") |
| return |
|
|
| |
| print("Attempting to set MJPG format...") |
| cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) |
| |
| |
| cap.set(cv2.CAP_PROP_FPS, fps) |
| cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) |
| cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) |
| |
| |
| |
| |
|
|
| |
| actual_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH) |
| actual_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) |
| actual_fps = cap.get(cv2.CAP_PROP_FPS) |
| fourcc = int(cap.get(cv2.CAP_PROP_FOURCC)) |
| codec = "".join([chr((fourcc >> 8 * i) & 0xFF) for i in range(4)]) |
| |
| print(f"----------------------------------------") |
| print(f"Requested: {width}x{height} @ {fps} FPS, MJPG") |
| print(f"Actual : {actual_w}x{actual_h} @ {actual_fps} FPS, Codec: {codec}") |
| print(f"----------------------------------------") |
| |
| if codec.upper() != "MJPG": |
| print("WARNING: Codec is NOT MJPG! This is likely the cause of low FPS.") |
|
|
| print("Warming up camera (skip 10 frames)...") |
| for _ in range(10): |
| cap.read() |
|
|
| print(f"Starting capture loop for 100 frames...") |
| count = 0 |
| start_time = time.time() |
| |
| while count < 100: |
| ret, frame = cap.read() |
| if not ret: |
| print("Error: Failed to read frame during loop") |
| break |
| count += 1 |
| |
| if count % 10 == 0: |
| sys.stdout.write(f"{count}..") |
| sys.stdout.flush() |
| |
| end_time = time.time() |
| duration = end_time - start_time |
| avg_fps = count / duration |
| |
| print(f"\n\nRESULT: Captured {count} frames in {duration:.2f} seconds.") |
| print(f"AVERAGE FPS: {avg_fps:.2f}") |
| |
| cap.release() |
|
|
| if __name__ == "__main__": |
| if len(sys.argv) < 2: |
| print("Usage: python test_camera_fps.py <device_id> [width] [height] [fps]") |
| print("Example: python backend/scripts/test_camera_fps.py 0 640 480 30") |
| else: |
| dev_id = int(sys.argv[1]) |
| w = int(sys.argv[2]) if len(sys.argv) > 2 else 640 |
| h = int(sys.argv[3]) if len(sys.argv) > 3 else 480 |
| f = int(sys.argv[4]) if len(sys.argv) > 4 else 30 |
| test_camera(dev_id, w, h, f) |
|
|
|
|