Advertisement
sombruxo

kk

Nov 22nd, 2024 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import rclpy
  2. from rclpy.node import Node
  3. from sensor_msgs.msg import Image, CompressedImage
  4. from cv_bridge import CvBridge
  5. import cv2
  6.  
  7. #https://docs.ros.org/en/indigo/api/cv_bridge/html/python/
  8.  
  9. class ImagePublisher(Node):
  10.  
  11. def __init__(self):
  12. super().__init__('Webcam_publisher')
  13. self.publisher_ = self.create_publisher(CompressedImage, '/webcam/image_raw/compressed', 1)
  14. timer_period = 0.333
  15. self.timer = self.create_timer(timer_period, self.timer_callback)
  16. self.cap = cv2.VideoCapture(0)
  17. if not self.cap.isOpened():
  18. print("VideoCapture error!!")
  19. exit()
  20. self.br = CvBridge()
  21.  
  22. def timer_callback(self):
  23. ret, frame = self.cap.read()
  24. if ret == True:
  25. self.publisher_.publish(self.br.cv2_to_compressed_imgmsg(frame, dst_format='jpg'))
  26. #self.publisher_.publish(self.br.cv2_to_compressed_imgmsg(frame, "bgr8"))
  27. self.get_logger().info('Publishing video frame')
  28.  
  29. def main(args=None):
  30. rclpy.init(args=args)
  31. image_publisher = ImagePublisher()
  32. rclpy.spin(image_publisher)
  33. image_publisher.destroy_node()
  34. rclpy.shutdown()
  35.  
  36. if __name__ == '__main__':
  37. main()
  38.  
  39.  
  40. ==========================================================================================================
  41.  
  42. import rclpy
  43. from rclpy.node import Node
  44. from sensor_msgs.msg import Image, CompressedImage
  45. from cv_bridge import CvBridge
  46. import cv2
  47.  
  48. class ImageSubscriber(Node):
  49.  
  50. def __init__(self):
  51. super().__init__('Webcam_subscriber')
  52. self.subscription = self.create_subscription(CompressedImage, '/webcam/image_raw/compressed', self.listener_callback, 1)
  53. self.subscription # prevent unused variable warning
  54. self.br = CvBridge()
  55.  
  56. def listener_callback(self, data):
  57. self.get_logger().info('Receiving video frame')
  58. current_frame = self.br.compressed_imgmsg_to_cv2(data)
  59. cv2.imshow("camera", current_frame)
  60. cv2.waitKey(1)
  61.  
  62. def main(args=None):
  63. rclpy.init(args=args)
  64. image_subscriber = ImageSubscriber()
  65. rclpy.spin(image_subscriber)
  66. image_subscriber.destroy_node()
  67. rclpy.shutdown()
  68.  
  69. if __name__ == '__main__':
  70. main()
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement