Advertisement
marichan022

mbanov_3_2.py

Jan 8th, 2022
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. import rclpy
  2. from rclpy.node import Node
  3. import cv2
  4. import numpy as np
  5. from cv_bridge import CvBridge
  6. from sensor_msgs.msg import Image
  7. from geometry_msgs.msg import Vector3, Twist
  8.  
  9.  
  10. r_min = 0
  11. g_min = 0
  12. b_min = 0
  13. r_max = 128
  14. g_max = 128
  15. b_max = 128
  16. f = 265.23
  17. u0 = 160.5
  18.  
  19.  
  20. class MyNode(Node):
  21.     def __init__(self):
  22.         super().__init__('mbanov_3_2')
  23.         self.create_subscription(Image, '/robot/camera/image', self.image_callback, 1)
  24.         self.pub_twist = self.create_publisher(Twist, '/robot/cmd_vel', 1)
  25.  
  26.     def image_callback(self, data):
  27.         frame = CvBridge().imgmsg_to_cv2(data)
  28.        
  29.         # Threshold the image - image is written in BGR format
  30.         frame_threshold = cv2.inRange(frame, (b_min, g_min, r_min), (b_max, g_max, r_max))
  31.         detected_pixels = np.transpose(np.nonzero(frame_threshold))
  32.        
  33.         if len(detected_pixels) == 0:  # BB-9 not detected
  34.             self.pub_twist.publish(Twist())
  35.             return
  36.        
  37.         u = np.mean(detected_pixels[:, 1])  # the middle point of the robot
  38.         beta = np.arctan2(u0 - u, f)
  39.        
  40.         twist = Twist()
  41.         twist.angular = Vector3(z=beta)
  42.         self.pub_twist.publish(twist)
  43.  
  44.  
  45. def main(args=None):
  46.     rclpy.init(args=args)
  47.     node = MyNode()
  48.     try:
  49.         rclpy.spin(node)
  50.     except KeyboardInterrupt:
  51.         rclpy.shutdown()
  52.  
  53.  
  54. if __name__ == '__main__':
  55.     main()
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement