line_follower.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 
00004 #This Program is tested on Gazebo Simulator
00005 #This script uses the cv_bridge package to convert images coming on the topic
00006 #sensor_msgs/Image to OpenCV messages and then convert their colors from RGB to HSV
00007 #then apply a threshold for hues near the color yellow to obtain the binary image 
00008 #to be able to see only the yellow line and then follow that line
00009 #It uses an approach called proportional and simply means 
00010 
00011 
00012 
00013 import rospy, cv2, cv_bridge, numpy
00014 from sensor_msgs.msg import Image
00015 from geometry_msgs.msg import Twist
00016 
00017 class Follower:
00018 
00019         def __init__(self):
00020                 
00021                 self.bridge = cv_bridge.CvBridge()
00022                 cv2.namedWindow("window", 1)
00023                 
00024                 self.image_sub = rospy.Subscriber('camera/rgb/image_raw',
00025                         Image, self.image_callback)
00026                 
00027                 self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop',
00028                         Twist, queue_size=1)
00029                 
00030                 self.twist = Twist()
00031 
00032         def image_callback(self, msg):
00033 
00034                 image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')
00035                 hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
00036                 lower_yellow = numpy.array([ 10, 10, 10])
00037                 upper_yellow = numpy.array([255, 255, 250])
00038                 mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
00039                 
00040                 h, w, d = image.shape
00041                 search_top = 3*h/4
00042                 search_bot = 3*h/4 + 20
00043                 mask[0:search_top, 0:w] = 0
00044                 mask[search_bot:h, 0:w] = 0
00045 
00046                 M = cv2.moments(mask)
00047                 if M['m00'] > 0:
00048                         cx = int(M['m10']/M['m00'])
00049                         cy = int(M['m01']/M['m00'])
00050                         cv2.circle(image, (cx, cy), 20, (0,0,255), -1)
00051 #The proportional controller is implemented in the following four lines which
00052 #is reposible of linear scaling of an error to drive the control output.        
00053                         err = cx - w/2
00054                         self.twist.linear.x = 0.2
00055                         self.twist.angular.z = -float(err) / 100
00056                         self.cmd_vel_pub.publish(self.twist)
00057                 cv2.imshow("window", image)
00058                 cv2.waitKey(3)
00059 
00060 rospy.init_node('line_follower')
00061 follower = Follower()
00062 rospy.spin()


gapter
Author(s):
autogenerated on Thu Jun 6 2019 22:05:13