# 摄像头画面测试程序 import os import cv2 import time import numpy as np import onnxruntime import win32com.client if __name__ == '__main__': # 摄像头索引号,通常为0表示第一个摄像头 camera_index = 3 # 打开摄像头 cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW) # 设置分辨率 cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2048) # 宽度 cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1540) # 高度 # 检查摄像头是否成功打开 if not cap.isOpened(): print("无法打开摄像头") exit() width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) print("摄像头分辨率:", width, "x", height) # 目标图像尺寸 # 计时器 frame_count = 0 start_time = time.time() stime = time.time() target_width = 1024 target_height = 768 # 循环读取摄像头画面 while True: ret, frame = cap.read() if not ret: print("无法读取摄像头画面") break resized_frame = frame if height > target_height and width > target_width: # 1920*1080的图像,中心裁剪640*480的区域 a = int(height / 2 - target_height / 2) b = int(height / 2 + target_height / 2) c = int(width / 2 - target_width / 2) d = int(width / 2 + target_width / 2) cropped_frame = frame[a:b, c:d] # 调整图像尺寸 resized_frame = cv2.resize(cropped_frame, (target_width, target_height)) # 计算帧速率 frame_count += 1 end_time = time.time() elapsed_time = end_time - start_time fps = frame_count / elapsed_time # print(f"FPS: {fps:.2f}") # 将FPS绘制在图像上 cv2.putText(resized_frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) resizeframe = cv2.resize(frame, (target_width, target_height)) # 显示画面 cv2.imshow("Camera", resizeframe) # 检测按键,如果按下q键则退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break # 关闭摄像头 cap.release() # 关闭所有窗口 cv2.destroyAllWindows()