LISHUZUOXUN_yangjiang/mp_test.py

55 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import cv2
import time
# 打开摄像头
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
# 设置摄像头帧率为30
cap.set(cv2.CAP_PROP_FPS, 35)
# 设置摄像头图像大小为640x480
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
# 检查摄像头是否成功打开
if not cap.isOpened():
print("Error: Could not open camera.")
exit()
# 定义一个计时器
start_time = time.time()
frame_counter = 0
fps = 0
while True:
# 读取一帧图像
ret, frame = cap.read()
if not ret:
print("Error: Could not read frame.")
break
# 计算帧率
frame_counter += 1
elapsed_time = time.time() - start_time
if elapsed_time > 1:
fps = frame_counter / elapsed_time
start_time = time.time()
frame_counter = 0
# 在图像上显示帧率
fps_text = f"FPS: {round(fps, 2)}"
print(fps_text)
cv2.putText(frame, fps_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
# 显示图像
cv2.imshow("Frame", frame)
# 检查是否按下了q键如果是则退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()