111 lines
3.4 KiB
Python
111 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
||
|
||
import os
|
||
import sys
|
||
import time
|
||
import cv2
|
||
|
||
# 添加父目录到路径,以便能够导入utils
|
||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from utils.image_raw import ImageProcessor
|
||
from utils.decode_arrow import detect_arrow_direction, visualize_arrow_detection
|
||
|
||
class ArrowDetector:
|
||
def __init__(self, image_processor=None):
|
||
"""
|
||
初始化箭头检测器
|
||
|
||
参数:
|
||
image_processor: 可选的ImageProcessor实例,如果不提供则会创建一个新的
|
||
"""
|
||
# 如果提供了图像处理器,则使用它,否则创建新的
|
||
if image_processor is not None:
|
||
self.image_processor = image_processor
|
||
self.should_destroy = False # 不应该在destroy方法中销毁外部传入的实例
|
||
else:
|
||
self.image_processor = ImageProcessor()
|
||
self.image_processor.run()
|
||
self.should_destroy = True # 应该在destroy方法中销毁自己创建的实例
|
||
|
||
print("箭头检测器已初始化")
|
||
|
||
def get_arrow_direction(self):
|
||
"""
|
||
获取当前图像中箭头的方向
|
||
|
||
返回:
|
||
direction: 字符串,"left"表示左箭头,"right"表示右箭头,"unknown"表示无法确定
|
||
"""
|
||
# 获取当前图像
|
||
image = self.image_processor.get_current_image()
|
||
|
||
if image is None:
|
||
print("警告: 无法获取图像")
|
||
return "unknown"
|
||
|
||
# 检测箭头方向
|
||
direction = detect_arrow_direction(image)
|
||
return direction
|
||
|
||
def visualize_current_detection(self, save_path=None):
|
||
"""
|
||
可视化当前图像的箭头检测过程
|
||
|
||
参数:
|
||
save_path: 保存结果图像的路径(可选)
|
||
"""
|
||
# 获取当前图像
|
||
image = self.image_processor.get_current_image()
|
||
|
||
if image is None:
|
||
print("警告: 无法获取图像")
|
||
return
|
||
|
||
# 可视化箭头检测
|
||
visualize_arrow_detection(image, save_path)
|
||
|
||
def destroy(self):
|
||
"""
|
||
清理资源
|
||
"""
|
||
if self.should_destroy:
|
||
self.image_processor.destroy()
|
||
print("箭头检测器已销毁")
|
||
|
||
def main():
|
||
"""
|
||
演示箭头检测器的用法
|
||
"""
|
||
try:
|
||
# 初始化箭头检测器
|
||
detector = ArrowDetector()
|
||
|
||
# 等待一段时间,确保图像已经接收
|
||
print("等待接收图像...")
|
||
time.sleep(3)
|
||
|
||
# 持续检测箭头方向
|
||
for i in range(10): # 检测10次
|
||
direction = detector.get_arrow_direction()
|
||
print(f"检测到的箭头方向 ({i+1}/10): {direction}")
|
||
|
||
# 可选: 保存第一次检测的可视化结果
|
||
if i == 0:
|
||
detector.visualize_current_detection("arrow_detection_result.jpg")
|
||
|
||
time.sleep(1) # 每秒检测一次
|
||
|
||
except KeyboardInterrupt:
|
||
print("\n程序被用户中断")
|
||
except Exception as e:
|
||
print(f"发生错误: {e}")
|
||
finally:
|
||
# 清理资源
|
||
print("正在清理资源...")
|
||
if 'detector' in locals():
|
||
detector.destroy()
|
||
print("程序已退出")
|
||
|
||
if __name__ == "__main__":
|
||
main() |