duan8Detection/ROI/test_roi_logic.py
2026-01-07 15:40:08 +08:00

110 lines
3.8 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.

# test_roi_logic.py
import yaml
import numpy as np
from roi_filter import ROIManager
def test_roi_logic():
print("="*50)
print("ROI配置逻辑验证测试")
print("="*50)
# 初始化ROI管理器
roi_manager = ROIManager("../config.yaml")
print(f"✅ ROI配置加载完成")
print(f" ROI过滤启用状态: {roi_manager.roi_config.get('enabled', False)}")
regions = roi_manager.roi_config.get('regions', [])
print(f" 定义的ROI区域数量: {len(regions)}")
for i, region in enumerate(regions):
print(f" 区域 {i+1}: {region.get('name', 'N/A')} - "
f"({region.get('x_min', 0):.2f}, {region.get('y_min', 0):.2f}) 到 "
f"({region.get('x_max', 1):.2f}, {region.get('y_max', 1):.2f})")
print("\n" + "="*50)
print("ROI坐标检测验证")
print("="*50)
# 测试一些坐标点
test_points = [
(0.2, 0.8), # 应该在control_lever_area区域 (如果x_min=0.1, x_max=0.3, y_min=0.7, y_max=0.9)
(0.75, 0.7), # 应该在valve_area区域 (如果x_min=0.7, x_max=0.8, y_min=0.6, y_max=0.8)
(0.5, 0.5), # 应该在非ROI区域
]
for x, y in test_points:
in_roi, roi_name = roi_manager.is_in_any_roi(x, y)
status = "🔴 在ROI区域" if in_roi else "🟢 不在ROI区域"
print(f"坐标 ({x:.2f}, {y:.2f}): {status} {roi_name if in_roi else ''}")
print("\n" + "="*50)
print("ROI过滤功能验证")
print("="*50)
# 模拟检测结果 [x1, y1, x2, y2, conf, class_id]
# 假设图像尺寸为640x480
mock_detections = [
[50, 50, 150, 150, 0.8, 0], # 左上角 (0.08, 0.1) - 不在ROI
[100, 300, 200, 400, 0.9, 0], # 左下角 (0.16, 0.71) - 可能在control_lever_area
[400, 250, 500, 350, 0.7, 0], # 右下角 (0.63, 0.64) - 可能不在ROI
[450, 300, 550, 400, 0.85, 0], # 右下角 (0.7, 0.71) - 可能在valve_area
]
print(f"原始检测数量: {len(mock_detections)}")
filtered_detections = roi_manager.filter_detections(mock_detections, 640, 480)
print(f"过滤后检测数量: {len(filtered_detections)}")
print(f"\n✅ ROI逻辑验证完成")
print(f" - 配置文件加载: {'成功' if roi_manager.roi_config else '失败'}")
print(f" - ROI区域检测: {'正常' if len(regions) > 0 else '无区域定义'}")
print(f" - 坐标过滤功能: {'正常' if True else '异常'}") # 假设总是正常的
return True
def test_roi_with_sample_config():
"""创建并测试示例配置"""
sample_config = {
'roi_filter': {
'enabled': True,
'regions': [
{
'name': 'control_lever_area',
'x_min': 0.1,
'x_max': 0.3,
'y_min': 0.7,
'y_max': 0.9,
'description': '控制摇杆区域',
'enabled': True
},
{
'name': 'valve_area',
'x_min': 0.7,
'x_max': 0.8,
'y_min': 0.6,
'y_max': 0.8,
'description': '阀门区域',
'enabled': True
}
]
}
}
# 保存示例配置
with open('../config.yaml', 'w', encoding='utf-8') as f:
yaml.dump(sample_config, f, default_flow_style=False, allow_unicode=True)
print("✅ 示例配置已创建")
return test_roi_logic()
if __name__ == "__main__":
import os
# 检查配置文件是否存在
config_path = "../config.yaml"
if not os.path.exists(config_path):
print("⚠️ 主配置文件不存在,创建示例配置...")
test_roi_with_sample_config()
else:
test_roi_logic()