#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import freetype
import cv2

class DetectSubscriber(Node):
    def __init__(self):
        super().__init__("detect_node")
        
        # 初始化CvBridge
        self.bridge = CvBridge()
        
        # 订阅detect话题
        self.subscription = self.create_subscription(
            Image,
            'detect',
            self.image_callback,
            10
        )
        
        self.subscription
        
        self.get_logger().info('检测节点已启动，正在监听 detect 话题...')
    
    def image_callback(self, msg):
        try:
            # 将ROS图像消息转换为OpenCV格式
            cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')
            
            # 显示图像
            cv2.imshow('Detect Image', cv_image)
            cv2.waitKey(1)
            
            # 输出图像信息
            self.get_logger().info(f'收到检测图像：{msg.width}x{msg.height}, 时间戳: {msg.header.stamp.sec}.{msg.header.stamp.nanosec}')
            
        except Exception as e:
            self.get_logger().error(f'处理图像失败：{str(e)}')

def main(args=None):
    rclpy.init(args=args)
    node = DetectSubscriber()
    
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        cv2.destroyAllWindows()
        node.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()
