214 lines
7.4 KiB
Python
214 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
分辨率性能测试脚本
|
||
测试不同分辨率下相机配置的性能差异
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
import time
|
||
import logging
|
||
|
||
# 添加项目路径
|
||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
from devices.camera_manager import CameraManager
|
||
from devices.utils.config_manager import ConfigManager
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||
)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
def test_resolution_performance(width, height, test_name):
|
||
"""
|
||
测试指定分辨率的性能
|
||
|
||
Args:
|
||
width: 宽度
|
||
height: 高度
|
||
test_name: 测试名称
|
||
|
||
Returns:
|
||
dict: 性能数据
|
||
"""
|
||
print(f"\n{'='*60}")
|
||
print(f"测试 {test_name}: {width}x{height}")
|
||
print(f"{'='*60}")
|
||
|
||
# 创建配置管理器并设置分辨率
|
||
config_manager = ConfigManager()
|
||
|
||
# 获取原始配置
|
||
original_config = config_manager.get_device_config('camera')
|
||
|
||
# 临时设置测试分辨率
|
||
test_config = {
|
||
'width': width,
|
||
'height': height
|
||
}
|
||
config_manager.set_camera_config(test_config)
|
||
|
||
try:
|
||
# 创建相机管理器
|
||
camera = CameraManager(None, config_manager)
|
||
|
||
# 测试初始化性能
|
||
start_time = time.time()
|
||
success = camera.initialize()
|
||
total_time = (time.time() - start_time) * 1000
|
||
|
||
if success:
|
||
print(f"✅ 初始化成功")
|
||
print(f"📊 总耗时: {total_time:.1f}ms ({total_time/1000:.1f}秒)")
|
||
|
||
# 获取实际分辨率
|
||
if camera.cap:
|
||
actual_width = int(camera.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||
actual_height = int(camera.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||
print(f"🎯 实际分辨率: {actual_width}x{actual_height}")
|
||
|
||
# 测试首帧获取
|
||
frame_start = time.time()
|
||
ret, frame = camera.cap.read() if camera.cap else (False, None)
|
||
frame_time = (time.time() - frame_start) * 1000
|
||
|
||
if ret and frame is not None:
|
||
print(f"🖼️ 首帧获取: {frame_time:.1f}ms, 帧大小: {frame.shape}")
|
||
else:
|
||
print(f"❌ 首帧获取失败")
|
||
frame_time = -1
|
||
|
||
# 清理资源
|
||
camera.cleanup()
|
||
|
||
return {
|
||
'resolution': f"{width}x{height}",
|
||
'success': True,
|
||
'total_time': total_time,
|
||
'frame_time': frame_time,
|
||
'actual_resolution': f"{actual_width}x{actual_height}" if camera.cap else "未知"
|
||
}
|
||
else:
|
||
print(f"❌ 初始化失败")
|
||
return {
|
||
'resolution': f"{width}x{height}",
|
||
'success': False,
|
||
'total_time': total_time,
|
||
'frame_time': -1,
|
||
'actual_resolution': "失败"
|
||
}
|
||
|
||
except Exception as e:
|
||
print(f"❌ 测试异常: {e}")
|
||
return {
|
||
'resolution': f"{width}x{height}",
|
||
'success': False,
|
||
'total_time': -1,
|
||
'frame_time': -1,
|
||
'actual_resolution': "异常",
|
||
'error': str(e)
|
||
}
|
||
finally:
|
||
# 恢复原始配置
|
||
try:
|
||
restore_config = {
|
||
'width': original_config['width'],
|
||
'height': original_config['height']
|
||
}
|
||
config_manager.set_camera_config(restore_config)
|
||
except Exception as e:
|
||
print(f"⚠️ 恢复配置失败: {e}")
|
||
|
||
def main():
|
||
"""
|
||
主测试函数
|
||
"""
|
||
print("🚀 开始分辨率性能测试")
|
||
|
||
# 测试不同分辨率
|
||
test_cases = [
|
||
(1280, 720, "当前分辨率"),
|
||
(640, 480, "标准VGA"),
|
||
(320, 240, "QVGA小分辨率"),
|
||
(160, 120, "极小分辨率")
|
||
]
|
||
|
||
results = []
|
||
|
||
for width, height, name in test_cases:
|
||
result = test_resolution_performance(width, height, name)
|
||
results.append(result)
|
||
|
||
# 等待一下,避免设备冲突
|
||
time.sleep(1)
|
||
|
||
# 输出汇总结果
|
||
print(f"\n{'='*80}")
|
||
print("📈 性能测试汇总")
|
||
print(f"{'='*80}")
|
||
|
||
print(f"{'分辨率':<15} {'状态':<8} {'初始化耗时':<12} {'首帧耗时':<10} {'实际分辨率':<15}")
|
||
print("-" * 80)
|
||
|
||
successful_results = []
|
||
|
||
for result in results:
|
||
status = "✅成功" if result['success'] else "❌失败"
|
||
init_time = f"{result['total_time']:.1f}ms" if result['total_time'] > 0 else "N/A"
|
||
frame_time = f"{result['frame_time']:.1f}ms" if result['frame_time'] > 0 else "N/A"
|
||
|
||
print(f"{result['resolution']:<15} {status:<8} {init_time:<12} {frame_time:<10} {result['actual_resolution']:<15}")
|
||
|
||
if result['success'] and result['total_time'] > 0:
|
||
successful_results.append(result)
|
||
|
||
# 性能分析
|
||
if len(successful_results) >= 2:
|
||
print(f"\n📊 性能分析:")
|
||
|
||
# 找到最快和最慢的
|
||
fastest = min(successful_results, key=lambda x: x['total_time'])
|
||
slowest = max(successful_results, key=lambda x: x['total_time'])
|
||
|
||
print(f"🏆 最快配置: {fastest['resolution']} - {fastest['total_time']:.1f}ms")
|
||
print(f"🐌 最慢配置: {slowest['resolution']} - {slowest['total_time']:.1f}ms")
|
||
|
||
if slowest['total_time'] > fastest['total_time']:
|
||
improvement = ((slowest['total_time'] - fastest['total_time']) / slowest['total_time']) * 100
|
||
print(f"💡 性能提升: {improvement:.1f}% (使用最小分辨率)")
|
||
|
||
# 基准对比
|
||
baseline = next((r for r in successful_results if "1280x720" in r['resolution']), None)
|
||
if baseline:
|
||
print(f"\n📋 相对于当前分辨率(1280x720)的性能对比:")
|
||
for result in successful_results:
|
||
if result != baseline:
|
||
if result['total_time'] < baseline['total_time']:
|
||
improvement = ((baseline['total_time'] - result['total_time']) / baseline['total_time']) * 100
|
||
print(f" {result['resolution']}: 快 {improvement:.1f}% ({result['total_time']:.1f}ms vs {baseline['total_time']:.1f}ms)")
|
||
else:
|
||
degradation = ((result['total_time'] - baseline['total_time']) / baseline['total_time']) * 100
|
||
print(f" {result['resolution']}: 慢 {degradation:.1f}% ({result['total_time']:.1f}ms vs {baseline['total_time']:.1f}ms)")
|
||
|
||
print(f"\n🎯 建议:")
|
||
if successful_results:
|
||
fastest = min(successful_results, key=lambda x: x['total_time'])
|
||
if fastest['total_time'] < 3000: # 小于3秒
|
||
print(f"✅ 推荐使用 {fastest['resolution']} 以获得最佳性能")
|
||
else:
|
||
print(f"⚠️ 即使最快的分辨率 {fastest['resolution']} 仍需 {fastest['total_time']:.1f}ms")
|
||
print(f" 建议考虑其他优化方案(如更换相机后端)")
|
||
else:
|
||
print(f"❌ 所有测试都失败了,请检查相机连接")
|
||
|
||
print(f"\n{'='*80}")
|
||
print("测试完成")
|
||
print(f"{'='*80}")
|
||
|
||
if __name__ == "__main__":
|
||
import cv2 # 在这里导入cv2,避免在函数中导入
|
||
main() |