follower_line_finder.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 #This script uses the cv_bridge package to convert images coming on the topic
00004 #sensor_msgs/Image to OpenCV messages and then convert their colors from RGB to HSV
00005 #then apply a threshold for hues near the color yellow to obtain the binary image 
00006 #to be able to see only the yellow line and then place a red dot in the middle of 
00007 #the yellow line at a distance 1 meter from the robot 
00008 
00009 import rospy, cv2, cv_bridge, numpy
00010 from sensor_msgs.msg import Image
00011 from geometry_msgs.msg import Twist
00012 
00013 class Follower:
00014 
00015         def __init__(self):
00016                 
00017                 self.bridge = cv_bridge.CvBridge()
00018                 cv2.namedWindow("window", 1)
00019                 self.image_sub = rospy.Subscriber('camera/rgb/image_raw',
00020                 Image, self.image_callback)
00021                 self.twist = Twist()
00022 
00023         def image_callback(self, msg):
00024                 
00025                 image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')          
00026                 hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
00027                 lower_yellow = numpy.array([ 10, 10, 10])
00028                 upper_yellow = numpy.array([255, 255, 250])
00029                 mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
00030 #use the OpenCV and numpy libraries to erase all the non matching pixels outside the
00031 #desired regions                
00032                 h, w, d = image.shape
00033                 search_top = 3*h/4
00034                 search_bot = search_top + 20
00035                 mask[0:search_top, 0:w] = 0
00036                 mask[search_bot:h, 0:w] = 0
00037                 
00038         #Using the moments() function to calculate the centroid or arithmetic centre
00039                 M = cv2.moments(mask)
00040                 if M['m00'] > 0:
00041                         cx = int(M['m10']/M['m00'])
00042                         cy = int(M['m01']/M['m00'])
00043         #Draw a circle at the centre of the desired region      
00044                         cv2.circle(image, (cx, cy), 20, (0,0,255), -1)
00045                 cv2.imshow("window", image)
00046                 cv2.waitKey(3)
00047 
00048 rospy.init_node('follower')
00049 follower = Follower()
00050 rospy.spin()


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