pick_object / test_camera_fps.py
yyyyyt's picture
Upload folder using huggingface_hub
b4e9cbc verified
Raw
History Blame
2.98 kB
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} ===")
# 优先使用 V4L2 后端
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
# 1. 强制 MJPG
print("Attempting to set MJPG format...")
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
# 2. 设置 FPS 和 分辨率
cap.set(cv2.CAP_PROP_FPS, fps)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
# 3. 关闭自动曝光 (Linux V4L2 特有,尝试通过 OpenCV 属性设置)
# 0.25 通常对应 'Manual',但在不同驱动下可能不同,这里仅作为尝试
# cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)
# 4. 读取实际生效的设置
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)