Following colored objects with your vision system

Now that your robot can sense colored objects, let's take this a step forward and use this capability to actually guide your robot. If you look at the code from the last section, you'll notice two variables, pt1 and pt2. These variables hold the x and y coordinates of the color that your robot found. We can use these with our dcmotor.py program to move the robot so that when the color reaches the edge of the viewing area, the robot will move to put the colored object back into the middle of the viewing area. Here is the code:

Following colored objects with your vision system

When your robot finds a color, it also finds the x boundaries of that color. These are held in the rect[0] and rect[2] variables. Each time through the loop, your program checks to see if the left side is smaller than 20 or the right side is larger than 310. In either case, your program will call the dcmotor.py program you wrote earlier and move the robot in a turn either to the right or left. As you move the target, the robot should turn with the object. The time_start and time_now variables allow you to slow the response of your robot. Otherwise, it will overturn. You might want to comment out the cvShowImage statement if your robot is struggling to keep up with the movement, as this statement does take some time.

You can also use the size of the color ball to decide how far the ball is, and then move the robot forward or backwards based on this size. Here is the while loop for that code, and it is the only part of the code you'll need to change:

Following colored objects with your vision system

The changes are simple. You will check the value of rect[2] which is the size of the color rectangle. If it is large enough, you move backward. If it is small enough, you will move forward.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.157.45